[LeetCode]941. Valid Mountain Array

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 some i with 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:

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

题目解析:这道题目就是让我们判断数组是否是“山”形的数组,数组长度不小于3,数组中某个数A[i],满足条件从下标0到i-1的数组元素依次增加,且A[i-1]<A[i],而从下标i+1到A.size()依次减少,且A[i]>A[i+1],是的A[i]是数组中最大的数。
思路:

  • 1、这道题目的思路就如题目所给,可以利用两个for循环来判断,当满足第一个条件时,break,之后判断是否满足第二个for循环,有一点需要主要的是,如果A[0]是最大的数值同样也会在两个for循环之间满足条件,所以需要区分这种情况。
class Solution {
public:
   bool validMountainArray(vector<int>& A) {
       if(A.size()<3)return false;
      // int res=0;
       int len=A.size();
       int cur=0;
       if(A[0]>A[1])return false;
       for(int i=0;i<len;i++)
       {
           if(A[i]>A[i+1])
              // res=A[i];
           {  cur=i;    
               break;}
       }
       
       for(int j=cur;j<len-1;j++)
       {
           if(A[j]<=A[j+1])return false;
       }
       return true;
   }
};

猜你喜欢

转载自blog.csdn.net/weixin_39116058/article/details/86545846