您的位置:首页 > 其它

#leetcode#Find Peak Element

2015-07-18 16:36 375 查看


Find Peak Element

 Total Accepted: 31990 Total
Submissions: 101250My Submissions

Question
 Solution 

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

= -∞
.
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.
Note:
Your solution should be in logarithmic complexity.

知道用binary search,但是一开始思路局限在nums[mid]要和nums[mid - 1], nums[mid + 1] 做比较来看nums[mid] 是否是 peak,这题只要返回任意一个peak就可以了, 这题给出条件 num[i] != num[i + 1], 算是个提示吧, 每次二分只要比较 nums[mid] 和 nums[mid + 1] 的大小关系就可以了

while(l < r){}, 最后返回 l 或者 r 都是可以的,因为while循环结束后 l == r

public class Solution {
public int findPeakElement(int[] nums) {
if(nums == null || nums.length == 0)
return -1;
int l = 0;
int r = nums.length - 1;
while(l < r){
int mid = l + (r - l) / 2;
if(nums[mid] > nums[mid + 1]){
r = mid;
}else{//nums[mid] < nums[mid + 1]
l = mid + 1;
}
}
return r;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode