刷题笔记
162. Find Peak Element
题目
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] = -∞.
思路
- 二分法查找,查找的条件思想很取巧:需要找到一个peak,则需要凑齐peak两侧的条件,对于右边,条件就是一个数比右侧数大;对于左边,条件就是一个数比左侧数小。
- 有了这个标准,开始搭建二分法查找,判断条件需要最后归拢到一个元素,即峰值元素,那么判断条件就是left < right。
- 而对于缩小范围,因为left和mid在只剩两个元素的时候是相等的,所以left要保持+1,来在最后一轮缩小范围;right则为了不错过峰值而取mid。
代码实现
class Solution {
public int findPeakElement(int[] nums) {
if (nums.length == 1) return 0;
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;
}
}