1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/go/find-peak-element.go
Matej Focko 0f02ef8e65
go: add «162. Find Peak Element»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-08-19 21:19:11 +02:00

31 lines
556 B
Go

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")
}