Skip to content

Latest commit

 

History

History
63 lines (57 loc) · 1.27 KB

852. 山脉数组的峰顶索引.md

File metadata and controls

63 lines (57 loc) · 1.27 KB

我们把符合下列属性的数组 A 称作山脉:

  • A.length >= 3
  • 存在 0 < i < A.length - 1 使得A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]

给定一个确定为山脉的数组,返回任何满足 A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 的 i 的值。 

示例 1:

输入:[0,1,0]
输出:1

示例 2:

输入:[0,2,1,0]
输出:1

提示:

  1. 3 <= A.length <= 10000
  2. 0 <= A[i] <= 10^6
  3. A 是如上定义的山脉

solution:

/**
 * 方法1
 * @param {number[]} A
 * @return {number}
 */
var peakIndexInMountainArray = function(A) {
    const len = A.length
    function middleCheck(i) {
        if (A[i] > A[i+1] && A[i] > A[i-1]) {
            return i
        } else if (A[i] > A[i+1] && A[i] < A[i-1]) {
            return middleCheck(i-1)
        } else if (A[i] < A[i+1] && A[i] > A[i-1]) {
            return middleCheck(i+1)
        }
    }
    return middleCheck(Math.floor(len / 2))
};
/**
 * 方法2
 * @param {number[]} A
 * @return {number}
 */
var peakIndexInMountainArray = function(A) {
    let i;
    let max = A[0];
    for(let j=1;j<A.length;j++) {
        if (A[j] > max) {
            max = A[j]
            i = j
        }   
    }
    return i
};