Find Peak Element
package main import "fmt" func findPeakElement(nums []int) int { left, right := 0, len(nums)-1 for left < right { mid := left + (right-left)/2 if nums[mid] > nums[mid+1] { right = mid } else { left = mid + 1 } } return left } func main() { nums1 := []int{1, 2, 3, 1} fmt.Printf("P...
This function finds a peak element in an array. A peak element is an element that is strictly greater than its neighbors. The array can contain multiple peaks, and the function is guaranteed to find one of them. This is...
The algorithm uses binary search to efficiently find a peak element. The core idea is that if nums[mid] < nums[mid+1], then a peak must exist to the right of mid (including mid+1), so we discard the left half. Conversely, if nums[mid] > nums[mid+1], a peak must exist at or to the left of mid, so we discard the right half. The loop invariant is that a peak element is guaranteed to exist within the range [left, right]. The time complexity is O(log n) because we halve the search space in each iteration. The space complexity is O(1) as we only use a few variables. Edge cases like a single-element array are handled correctly as the loop condition `left < right` will not be met, and `left` (which is 0) will be returned, which is the peak.
function findPeakElement(nums): left = 0 right = length(nums) - 1 while left < right: mid = left + floor((right - left) / 2) if nums[mid] > nums[mid + 1]: right = mid else: left = mid + 1 return left