LeetCode Solutions
162. Find Peak Element
Time: $O(\log n)$ Space: $O(1)$
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int l = 0;
int r = nums.size() - 1;
while (l < r) {
const int m = (l + r) / 2;
if (nums[m] >= nums[m + 1])
r = m;
else
l = m + 1;
}
return l;
}
};
class Solution {
public int findPeakElement(int[] nums) {
int l = 0;
int r = nums.length - 1;
while (l < r) {
final int m = (l + r) / 2;
if (nums[m] >= nums[m + 1])
r = m;
else
l = m + 1;
}
return l;
}
}
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
l = 0
r = len(nums) - 1
while l < r:
m = (l + r) // 2
if nums[m] >= nums[m + 1]:
r = m
else:
l = m + 1
return l