website/content.en/ChapterFour/0800~0899/0852.Peak-Index-in-a-Mountain-Array.md
Let's call an array A a mountain if the following properties hold:
A.length >= 30 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].
Example 1:
Input: [0,1,0]
Output: 1
Example 2:
Input: [0,2,1,0]
Output: 1
Note:
3 <= A.length <= 100000 <= A[i] <= 10^6We call an array A that satisfies the following properties a mountain:
Note:
i is greater than the elements at positions i-1 and i+1). Find this "peak" and output the index of one peak.
package leetcode
// Solution 1: Binary search
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
}
// Solution 2: Binary search
func peakIndexInMountainArray1(A []int) int {
low, high := 0, len(A)-1
for low < high {
mid := low + (high-low)>>1
// If mid is larger, then a peak exists on the left, high = m; if mid + 1 is larger, then a peak exists on the right, low = mid + 1
if A[mid] > A[mid+1] {
high = mid
} else {
low = mid + 1
}
}
return low
}