162. Find Peak Element
Problem Statement
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.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Constraints:
1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
nums[i] != nums[i + 1]
for all validi
.
Intuition
Approach:
There is increasing curve, Then peak, Then decreasing
We find at each step if we are at increasing or decreasing
And move like that
Links
https://leetcode.com/problems/find-peak-element/description/
Video Links
https://www.youtube.com/watch?v=cXxmbemS6XM&ab_channel=takeUforward
Approach 1:
class Solution {
public:
int findPeakElement(vector<int>& nums) {
for(int i=0; i<nums.size(); i++){
if(i==0){
if(i+1 < nums.size() and nums[i] > nums[i+1])
return i;
}
else if(i == nums.size()-1){
if(nums[i] > nums[i-1])
return i;
}
else{
if(nums[i-1] < nums[i] and nums[i] > nums[i+1])
return i;
}
}
return 0;
}
};
Approach 2:
class Solution {
public:
int findPeakElement(vector<int>& nums) {
for(int i=0; i<nums.size()-1; i++){
if(nums[i]>nums[i+1])
return i;
}
return nums.size()-1;
}
};
Approach 3:
OPtimal
class Solution {
public:
int find_ans(vector<int>& arr, int low, int high){
while(low<=high){
int mid = low+(high-low)/2;
if(arr[mid-1] < arr[mid] and arr[mid] > arr[mid+1])
return mid;
else if(arr[mid-1] < arr[mid])
low = mid+1;
else
high=mid-1;
}
return -1;
}
int findPeakElement(vector<int>& nums) {
int n = nums.size();
if(n == 1 or nums[0] > nums[1])
return 0;
if(nums[n-1] > nums[n-2])
return n-1;
return find_ans(nums,1, n-2);
}
};
Approach 4:
Similar Problems
Previous34. Find First and Last Position of Element in Sorted ArrayNext33. Search in Rotated Sorted Array
Last updated