难度中等662收藏分享切换为中文接收动态反馈
A peak element is an element that is strictly greater than its neighbors.
Given an integer array
nums
, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.You may imagine that
nums[-1] = nums[n] = -∞
.You must write an algorithm that runs in
O(log n)
time.Example 1:
Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2.Example 2:
Input: nums = [1,2,1,3,5,6,4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.Constraints:
1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
nums[i] != nums[i + 1]
for all validi
.通过次数174,411提交次数351,484
这题的思路是用二分法,可能大家接触的二分法都是有序的元素,这一题其实就是求区域峰值问题,简单点说,跟我们高中学弟单调性有点像,所有每个最大值都代表了一个峰值,我们只要找到那个中间位置的元素,就意味着可以一直使用二分法进行求解
class Solution {
public int findPeakElement(int[] nums) {
int low = 0;
int high = nums.length - 1;
return Helper(nums,low,high);
}
public int Helper(int[] num,int low,int high){
//真正的输出
if(low == high)
return low;
else {
//中间元素
int mid1 = (low+high)/2;
//中间元素的后一个元素
int mid2 = mid1+1;
if(num[mid1] > num[mid2])
return Helper(num, low, mid1);
else
return Helper(num, mid2, high);
}
}
}