go: add «162. Find Peak Element»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
9f9d400b2d
commit
0f02ef8e65
1 changed files with 31 additions and 0 deletions
31
go/find-peak-element.go
Normal file
31
go/find-peak-element.go
Normal 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")
|
||||
}
|
Loading…
Reference in a new issue