题解 | #寻找峰值#
寻找峰值
http://www.nowcoder.com/practice/fcf87540c4f347bcb4cf720b5b350c76
二分
二分查找的灵活运用,nums[mid]和nums[mid+1]进行比较。若nums[mid] < nums[mid+1],说明在上升,l = mid + 1;若nums[mid] > nums[mid+1],说明在下降,r = mid。
C++代码:
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while (l < r) {
int mid = (l + r) / 2;
if (nums[mid] < nums[mid + 1]) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
}
};