# Untitled

unknown
c_cpp
a year ago
1.7 kB
4
Indexable
Never
```// aman jain mca 1st year 2nd shift

class Solution {
public:
int findPeakElement(vector<int>& nums) {
int ans = 0, left = 0, right = nums.size() - 1;
while(left <= right) {
int mid = (left + right)/2;
if(mid - 1 >= 0 && mid + 1 <= nums.size() - 1) { // both neighbours in range
if(nums[mid - 1] < nums[mid] && nums[mid + 1] < nums[mid]) { // peak made
ans = mid;
break;
}
else if(nums[mid - 1] > nums[mid]) { // possible peak to the left of mid
right = mid - 1;
}
else { // possible peak to the right of mid
left = mid + 1;
}
}
else if(mid - 1 < 0 && mid + 1 >= nums.size()) { // both neighbours out of range
ans = mid;
break;
}
else if(mid + 1 >= nums.size()) { // right neighbour out of range
if(nums[mid - 1] < nums[mid]) { // peak made
ans = mid;
break;
}
else { // possible peak to the left of mid
right = mid - 1;
}
}
else { // left neighbour out of range
if(nums[mid + 1] < nums[mid]) { // peak made
ans = mid;
break;
}
else { // possible peak to the right of mid
left = mid + 1;
}
}
}
return ans;
}
};```