LeetCode 162: Find Peak Element Solution
Master LeetCode problem 162 (Find Peak Element), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
162. Find Peak Element
Problem Explanation
Explanation:
To find a peak element in an array, we can use a binary search approach to achieve O(log n) time complexity. The key idea is to compare the middle element with its neighbors to determine if the peak lies to the left or right of it.
- Initialize low to 0 and high to the length of the array - 1.
- While low is less than high:
- Calculate mid as (low + high) / 2.
- Compare nums[mid] with its neighbors nums[mid-1] and nums[mid+1].
- If nums[mid] is greater than both neighbors, return mid as the peak.
- If nums[mid+1] is greater, update low = mid + 1 to search in the right half.
- If nums[mid-1] is greater, update high = mid - 1 to search in the left half.
- At the end of the loop, low will be at the peak element index.
Solution Code
class Solution {
public int findPeakElement(int[] nums) {
int low = 0, high = nums.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (nums[mid] > nums[mid + 1]) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 162 (Find Peak Element)?
This page provides optimized solutions for LeetCode problem 162 (Find Peak Element) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 162 (Find Peak Element)?
The time complexity for LeetCode 162 (Find Peak Element) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 162 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 162 in Java, C++, or Python.