Files
LeetCode-Go/leetcode/0852.Peak-Index-in-a-Mountain-Array/852. Peak Index in a Mountain Array.go
2020-08-07 17:06:53 +08:00

35 lines
721 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package leetcode
// 解法一 二分
func peakIndexInMountainArray(A []int) int {
low, high := 0, len(A)-1
for low <= high {
mid := low + (high-low)>>1
if A[mid] > A[mid+1] && A[mid] > A[mid-1] {
return mid
}
if A[mid] > A[mid+1] && A[mid] < A[mid-1] {
high = mid - 1
}
if A[mid] < A[mid+1] && A[mid] > A[mid-1] {
low = mid + 1
}
}
return 0
}
// 解法二 二分
func peakIndexInMountainArray1(A []int) int {
low, high := 0, len(A)-1
for low < high {
mid := low + (high-low)>>1
// 如果 mid 较大则左侧存在峰值high = m如果 mid + 1 较大则右侧存在峰值low = mid + 1
if A[mid] > A[mid+1] {
high = mid
} else {
low = mid + 1
}
}
return low
}