[每日LeetCode] 941. Valid Mountain Array

  |   0 评论   |   671 浏览

原文链接 [每日LeetCode] 941. Valid Mountain Array

Description:

Given an array A of integers, return true if and only if it is a_valid mountain array_.

Recall that A is a mountain array if and only if:

  • A.length >= 3
  • There exists someiwith 0 < i < A.length - 1 such that:
    • A[0] < A[1] < ... A[i-1] < A[i]
    • A[i] > A[i+1] > ... > A[B.length - 1]

Example 1:

Input: [2,1]
Output: false

Example 2:

Input: [3,5,5]
Output: false

Example 3:

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

Note:

  1. 0 <= A.length <= 10000
  2. 0 <= A[i] <= 10000 

我的思路:题目要求判断一个数组是是否只有一个“驼峰”,可使用两个指针分别同时从数组两头往中间爬,最后判断两个指针指向的值是否相等并且位置在数组范围内。


我的C++代码

class Solution {
public:
    bool validMountainArray(vector<int>& A) {
      int size = A.size();
      int i=0, j=size-1;
      while(i+1<size && A[i] < A[i+1])
        i++;
      while(j>0 && A[j-1] > A[j])
        j--;
      return i > 0 && i==j && j < size - 1;
    }
};

运行时间:40ms
运行内存:10.6M


评论

发表评论