[LeetCode] 852. Peak Index in a Mountain Array

Easy

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].

Example 1:

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

Example 2:

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

Note:

  1. 3 <= A.length <= 10000
  2. 0 <= A[i] <= 10^6
  3. A is a mountain, as defined above.

题目大意:当一个数组A满足一下两个条件时,我们称之为山峰:

1.数组的长度>=3

2.对于0<i<A.length,有A[0]<A[1]<...<A[i]>A[i+1]>...>A[A.length]

找出山峰数组中的峰值所对应的引索i。

 

这道题中的数组是已经排好序的,峰值前的数列是非降序排列,峰值后的数列是非升序排列。所以只要从前往后找到第一个不是降序排列的数字就找到了峰值点。

代码如下:

class Solution {
public:
    int peakIndexInMountainArray(vector<int>& A) {
        int len=A.size();
        
        for(int i=1;i<len-1;++i){
            if(A[i]>A[i-1] && A[i]>A[i+1]){
                return i;
            }
        }
        if(len>1 && A[len-1]>A[len-2])return len-1;
        return 0;
    }
};

 

posted @ 2019-09-02 13:48  程嘿嘿  阅读(115)  评论(0编辑  收藏  举报