mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 162. Find Peak Element.md
This commit is contained in:
parent
a4bf658926
commit
c33b15eeeb
30
solutions/162. Find Peak Element.md
Normal file
30
solutions/162. Find Peak Element.md
Normal file
@ -0,0 +1,30 @@
|
||||
# [162. Find Peak Element](https://leetcode.com/problems/find-peak-element/)
|
||||
# 思路
|
||||
寻找一个数组中的极大值. 由于要求对数复杂度, 所以我们很容易想到二分法.
|
||||
由于题目说了nums[-1]和nums[n]为负无穷, 那么极大值一定存在(想象一下被山谷包围的山脉).
|
||||
|
||||
那么在二分的循环中:
|
||||
1. 若`mid == 0 || nums[mid-1] < nums[mid]`, 即mid左边是上升趋势, 那么mid或者其右边一定存在极大值;
|
||||
2. 满足1且`mid == n - 1 || nums[mid] > nums[mid+1]`, 即mid就是极大值;
|
||||
3. 满足1但不满足2, 那么其右边一定存在极大值, 此时更新`low = mid + 1`;
|
||||
4. 否则, mid左边一定存在极大值, 此时更新`high = mid - 1`;
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
class Solution {
|
||||
public:
|
||||
int findPeakElement(vector<int>& nums) {
|
||||
int n = nums.size();
|
||||
int low = 0, high = n - 1, mid;
|
||||
while(low < high){
|
||||
mid = low + (high - low) / 2;
|
||||
if(mid == 0 || nums[mid-1] < nums[mid]){
|
||||
if(mid == n - 1 || nums[mid] > nums[mid+1]) return mid; // 找到
|
||||
else low = mid + 1;
|
||||
}
|
||||
else high = mid - 1;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user