LeetCode: 852. Peak Index in a Mountain Array

題目:

Let’s call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < 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].

範例:

Input: [0,1,0]
Output: 1
Input: [0,2,1,0]
Output: 1

這題是要找出山峰的位置
我解的時候
是判斷要與left、right的點作比較
但後來看到其它人解法
其實只要判斷第一個下降的位置就好了
看來想法還是不到位

解法:

func peakIndexInMountainArray(A []int) int {
    var index int
    for i := 1; i < len(A)-1; i++{
        if A[i-1] < A[i] && A[i] > A[i+1] {
            index = i
            break
        }
    }
    return index
}

發佈留言