Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions LeetCode/Find peak element
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
A peak element is an element that is strictly greater than its neighbors.

Given a 0-indexed 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] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.

You must write an algorithm that runs in O(log n) time.



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.


class Solution {
public:
int findPeakElement(vector<int>& nums) {

int l = 0, r = nums.size() - 1, mid;
while (l < r) {
mid = (l + r) / 2;
if (nums[mid] < nums[mid + 1])
l = mid + 1;
else
r = mid;
}
return l;

}
};