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[-1]和num[n]算上, 比如单调递增的num[n-1]就是一个peak.
binary search 基本题,注意结束条件的判断用loop invariant的思想:
1. 初始化
2. loop invariant.
3. 结束: 首先是能够结束,每次的range都要缩小. 然后是结束条件达到时(start==end)结果正确
public class Solution {
public int findPeakElement(int[] num) {
if(num==null || num.length==0)return -1;
int start=0, end=num.length-1;
while(start<end)
{
int mid=(start+end)/2;
if(num[mid]>num[mid+1])
{
end=mid;
}
else
{
start=mid+1;
}
}
if(start==end)return start;
else return -1;
}
}