用二分法找到数组山峰值

来源:互联网 发布:淘宝怎么开直播卖衣服 编辑:程序博客网 时间:2024/05/19 02:18
<span style="font-family: Arial, Helvetica, sans-serif;">public int findPeakElement(int[] nums) {</span>
    int N = nums.length;    if (N == 1) {        return 0;    }    int left = 0, right = N - 1;    while (right - left > 1) {        int mid = left + (right - left) / 2;        if (nums[mid] < nums[mid + 1]) {            left = mid + 1;        } else {            right = mid;        }    }    return (left == N - 1 || nums[left] > nums[left + 1]) ? left : right;}

162. Find Peak Element

 My Submissions
Total Accepted: 68516 Total Submissions: 206717 Difficulty: Medium

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.

click to show spoilers.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

总结:一直以来对二分法的研究只是局限于在有序数据的查找中使用,在上面使用二分法题目中有效的降低了算法的时间复杂度。

if(nums[mid]<nums[mid+1])

  left=mid+1;

这就使得left比左边的数大,同理使得right比右边的数大,这样在left和right相邻时,比较left和right的大小就可以得出峰值。



0 0
原创粉丝点击