LeetCode/go/find-peak-element.go

32 lines
556 B
Go
Raw Normal View History

package main
func findPeakElement(nums []int) int {
length := len(nums)
check := func(i int) bool {
return (i == 0 || nums[i-1] < nums[i]) && (i == length-1 || nums[i] > nums[i+1])
}
if check(0) {
return 0
} else if check(length - 1) {
return length - 1
}
left, right := 1, length-2
for left <= right {
mid := (left + right) / 2
if check(mid) {
return mid
} else if nums[mid] < nums[mid-1] {
right = mid - 1
} else if nums[mid] < nums[mid+1] {
left = mid + 1
}
}
panic("unreachable: peak element is guaranteed")
}