###### tags: `LeetCode` `Binary Search` `Medium` # LeetCode #162 [Find Peak Element](https://leetcode.com/problems/find-peak-element/) ### (Medium) 峰值元素是指其值嚴格大於左右相鄰值的元素。 給你一個整數數組 nums,找到峰值元素並返回其索引。數組可能包含多個峰值,在這種情況下,返回 任何一個峰值 所在位置即可。 你可以假設 nums[-1] = nums[n] = -∞ 。 你必須實現時間複雜度為 O(log n) 的算法來解決此問題。 --- 當中點的左邊的值大於中點的值時, 左邊必定有一個峰值(因為nums[-1]為負無限), 反之若左邊的值小於中點的值, 則中點到nums.size()-1間必有峰值(同理, 對中點-1來說, 中點高於它, 所以中點-1的右邊必有峰值)。 注意是否會產生死循環, 還有左閉右開或是左閉右閉的選擇。 --- ``` class Solution { public: int findPeakElement(vector<int>& nums) { int l=0, r=nums.size()-1; while(l<r){ int m=l+(r-l+1)/2;//確認是否有死循環 if(nums[m]<nums[m-1])r=m-1; else l=m; } return l; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up