162. Find Peak Element
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.
解法
二分查找,如果比后一个元素大,则往左走;如果比后一个元素小,则往右走
public class Solution {
public int findPeakElement(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
int mid;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (nums[mid] < nums[mid + 1]) {
start = mid;
} else {
end = mid;
}
}
return nums[start] > nums[end] ? start : end;
}
}
本文介绍了一种使用二分查找算法寻找峰值元素的方法。峰值元素是指大于其相邻元素的元素,在数组中可能存在多个峰值,返回任意一个即可。文章给出了具体的实现代码。
234

被折叠的 条评论
为什么被折叠?



