162. 寻找峰值

package leetcode;

//nums[mid+1]>nums[mid],那么mid+2只有两种可能,一个是大于mid+1,一个是小于mid+1,小于mid+1的情况,那么mid+1就是峰值,
//大于mid+1的情况,继续向右推,如果一直到数组的末尾都是大于的,那么可以肯定最后一个元素是峰值,因为nums[nums.length]=负无穷
//num[mid+1]<nums[mid]同理
public class demo_162 {
    public int findPeakElement(int[] nums) {
        int left=0;
        int right=nums.length-1;
        int mid=0;
        while(left<=right) {
            mid=(left+right)/2;
            //nums[mid+1]>nums[mid]情况
            if((mid+1)<nums.length&&nums[mid]<nums[mid+1]) {
                if((mid+2)==nums.length||nums[mid+2]<nums[mid+1]) {
                    return (mid+1);
                }
                else {
                    left=mid+1;
                }
            }
            //nums[mid+1]<nums[mid]情况
            else {
                if((mid-1)>-1&&nums[mid]>nums[mid-1]) {
                    return mid;
                }
                else {
                    right=mid-1;
                }
            }
        }
        return mid;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        demo_162 d162=new demo_162();
        int[] nums= {1,2};
        System.out.println(d162.findPeakElement(nums));
    }

}

 

上一篇:leetcode之162寻找峰值Golang


下一篇:leetcode 162. Find Peak Element | 162. 寻找峰值(待完善)