Find Peak Element (M)
A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[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 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: 1 or 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.
Note:
Your solution should be in logarithmic complexity.
题意
给定一个整数数组,将所有整数按顺序连成一条折线图,要求找到其中任意一个极大值的下标(下标-1和n对应的值为负无穷)。解法的时间复杂度应为O(NlogN)O(NlogN)O(NlogN)。
思路
很明显是要使用二分法查找,问题只需要找到任意一个元素,使其比前后两个元素都大。
代码实现
class Solution {
public int findPeakElement(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[mid + 1]) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
本文介绍了一种使用二分法在给定数组中寻找峰值元素的方法,峰值元素是指比其邻居大的元素。通过递归缩小搜索范围,算法能在O(logN)的时间复杂度内找到一个峰值的下标。
233

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



