162. Find Peak Element(重要)

来源:互联网 发布:webshell是什么 编辑:程序博客网 时间:2024/06/05 17:05

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.

1.如果nums[mid] > nums[mid - 1]且nums[mid] > nums[mid + 1],则,返回mid

2.如果nums[mid]  < nums[mid - 1],则[left,mid-1]部分一定存在peak,

因为如果nums[mid-2]也小于nums[mid - 1],则nums[mid - 1]是peak;否则继续在[left,mid-2]范围查找。

3.类似

class Solution {public:int findPeakElement(vector<int>& nums) {int n = nums.size();int left = 0, right = n - 1;int mid;while (left <= right){mid = left + (right - left) / 2;if ((mid == 0 || nums[mid] > nums[mid - 1]) && (mid == n - 1 || nums[mid] > nums[mid + 1])){return mid;}else if (mid>0 && nums[mid] < nums[mid - 1]){    right = mid - 1;}else{left = mid + 1;}}return -1;}};


0 0