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

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.

简单题,就理解成找最大值的index
Moutain都是先上后下的一个形状,对下降的那个节点做判断就能得出结果

算法复杂度\(O(n)\)

int peakIndexInMountainArray(vector<int>& A) {
    int i = 1;
    while (i <= A.size())
    {
        if (A.at(i-1) > A.at(i))
        {
            return i-1;
        }
        ++i;
    }
}

这样提交上去的结果不是很好,做一些修改

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    int peakIndexInMountainArray(vector<int>& A) {
        for (int i = 1; i <= A.size(); i++)
        {
            if (A.at(i-1) > A.at(i))
            {
                return i-1;
            }
        }
    }
};

还可以直接找最大值的index,甚至都不用自己写,直接调函数,这样就beat 100.00%了

int peakIndexInMountainArray(vector<int>& A) 
{
    vector<int>::iterator max_iter = max_element(A.begin(), A.end());
    return distance(A.begin(), max_iter);
}

LeetCode上其他的解法有用二分的,理论上要快点,这里就不写了

posted @ 2018-08-03 09:57  arcsinW  阅读(345)  评论(0编辑  收藏  举报