Find Peak Element in Sorted Array
int FindPeakElement(const TArray<int>& nums) { int left = 0; int right = nums.Num() - 1; while (left < right) { int mid = left + (right - left) / 2; // Check if mid is a peak if (nums[mid] > nums[mid + 1] && nums[mid] > nums[mid - 1]) { return mid; // Found a peak } // If the rig...
This function finds a peak element in an array where elements are not necessarily sorted but have the property that nums[i] != nums[i+1]. A peak element is defined as an element that is strictly greater than its neighbor...
The algorithm uses binary search to efficiently find a peak element. The key insight is that if an element `nums[mid]` is not a peak, then either its left neighbor or its right neighbor must be greater. If `nums[mid+1]` is greater, a peak must exist in the right half (including `mid+1`). If `nums[mid-1]` is greater (or `nums[mid+1]` is not greater), a peak must exist in the left half (including `mid`). This process halves the search space in each step, leading to a time complexity of O(log n). The space complexity is O(1) as it only uses a few variables. Edge cases like single-element arrays or peaks at the array boundaries are implicitly handled by the loop condition and the way `left` and `right` are updated. The invariant maintained is that a peak element is guaranteed to exist within the `[left, right]` range.
function FindPeakElement(nums): left = 0 right = length(nums) - 1 while left < right: mid = left + (right - left) / 2 if nums[mid] < nums[mid + 1]: left = mid + 1 else: right = mid return left