LeetCode Find Peak Element(二分查找法)

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

题意:给出一个数组,num[i] != nusm[i +1],并且num[-1]=num[n]=负无穷大,求极点

思路:用二分查找法,如果num[mid-1]> num[mid],说明在左半部,如果num[mid +1]> num[mid],说明在右半部,否则,mid就是要找的位置

代码如下:

class Solution
{
    public int findPeakElement(int[] nums)
    {
        int low = 0, high = nums.length - 1;

        while (low < high)
        {
            int mid = (low + high) >> 1;
            if (mid > 0 && nums[mid - 1] > nums[mid])
            {
                high = mid - 1;
            }
            else if (mid < nums.length - 1 && nums[mid + 1] > nums[mid])
            {
                low = mid + 1;
            }
            else
            {
                return mid;
            }
        }
        return low;
    }
}


你可能感兴趣的:(LeetCode Find Peak Element(二分查找法))