题目描述:
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.
在一个序列中,找到nums[i] > nums[i-1] && nums[i] > nums[i+1]的索引i。
本题可以理解为在1个不连续的点集中,找到极大值点(先增后减)。
本题是一个典型的二分法查询问题:
1.如果序列本身是递减,nums[0]就是极大值点。
2.如果序列末尾处递增,nums[len -1]就是极大值点。
3.如果nums[i] > nums[i+1] 且 nums[i] > nums[i-1],那么nums[i]就是极大值。
4.如果序列在nums[i]处递增,即nums[i-1] < nums[i] < nums[i+1],那么右边一定存在极大值。
5.如果序列在nums[i]处递减,即nums[i-1] > nums[i] > nums[i+1],左边一定存在极大值。
实现代码:
public class Solution {
public int FindPeakElement(int[] nums) {
if(nums.Length == 0){
return -1;
}
if(nums.Length == 1){
return 0;
}
if(nums.Length == 2){
return nums[0] > nums[1] ? 0 : 1;
}
if(nums[nums.Length - 1] > nums[nums.Length - 2]){
return nums.Length -1;
}
if(nums[0] > nums[1]){
return 0;
}
var l = 0;
var r = nums.Length - 1;
while(l < r - 1){
var m = (l + r) / 2;
if(nums[m] > nums[m-1] && nums[m] > nums[m+1]){
return m;
}
else if(nums[m] > nums[m-1] && nums[m] < nums[m+1]){ // increasing , go right
l = m;
}
else { // decreasing , go left
r = m;
}
}
return -1;
}
}