问题
A peak element is an element that is strictly greater than its neighbors.
Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Constraints:
- 1 <= nums.length <= 1000
- -231 <= nums[i] <= 231 - 1
- nums[i] != nums[i + 1] for all valid i.
Follow up: Could you implement a solution with logarithmic complexity?
方法1
最简单的方法就是遍历,从头到尾遍历一边, 除了第一个和最后一个以外, 其他的位置比较前后两个元素的大小.
时间复杂度
O
(
n
)
O(n)
O(n).
空间复杂度
O
(
1
)
O(1)
O(1).
class Solution {
public int findPeakElement(int[] nums) {
int len = nums.length;
if(len == 1 || nums[0] > nums[1])
return 0;
if(nums[len - 1] > nums[len - 2])
return len - 1;
for(int i = 1; i < len - 1; i++)
if(nums[i] > nums[i-1] && nums[i] > nums[i + 1])
return i;
return 0;
}
}
方法2
用binarysearch的变种来做、总是往大的那边继续查找,较小的那一边放弃, 就可以做到 O ( log n ) O(\log n) O(logn)的复杂度.
时间复杂度
O
(
log
n
)
O(\log n)
O(logn).
空间复杂度
O
(
n
)
O(n)
O(n).
class Solution {
public int findPeakElement2(int[] nums) {
int left = 0, right = nums.length - 1;
while(left < right){
int mid = (left + right) / 2;
if(nums[mid] > nums[mid + 1])
right = mid;
else
left = mid + 1;
}
return left;
}
}