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.
题意:给定一个相邻元素不相等的数组,返回任意一个局部最大值的下表。
方法一:二分查找(logn)
如果中间位置元素大于其相邻后续元素,则数组左侧部分元素必定存在局部最大值;否则,则数组右侧部分元素必定存在局部最大值。
public class Solution {
public int findPeakElement(int[] nums) {
if (nums.length == 1) {
return 0;
}
int left = 0;
int right = nums.length - 1;
int mid = 0;
int result = 0;
while (left <= right) {
if (left == right) {
result = left;
break;
}
mid = (left + right) / 2;
if (nums[mid] < nums[mid + 1]) {
left = mid + 1;
} else {
right = mid;
}
}
return result;
}
}
方法二:顺序查找(O(n))
题目中有:num[-1] = num[n] = -∞
.
如果num[0] > num[1],则num[0]是一个局部最大值;
如果num[n - 1] > num[n - 1 - 1],则num[n-1]是一个局部最大值。
从第一个元素开始遍历数组,当满足num[i] > num[i + 1] (也就是num[0] < num[1] < ... < num[i])时停止,则num[i]是局部最大值。如果i= n - 2时,依然是num[n - 2] < num[n - 1],那么局部最大值就是num[n - 1]
public class Solution {
public int findPeakElement(int[] nums) {
for (int i = 1; i < nums.length; ++i) {
if (nums[i] < nums[i - 1]) {
return i - 1;
}
}
return nums.length - 1;
}
}