162. Find Peak Element
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.
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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.