1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

go: add «162. Find Peak Element»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-19 21:19:11 +02:00
parent 9f9d400b2d
commit 0f02ef8e65
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

31
go/find-peak-element.go Normal file
View file

@ -0,0 +1,31 @@
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")
}