Question:
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
with0 < 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:
Input: [2,1]
Output: false
Input: [3,5,5]
Output: false
Input: [0,3,2,1]
Output: true
Solution:
/**
* @param {number[]} A
* @return {boolean}
*/
var validMountainArray = function(A) {
// 数组长度大于3
if ( A.length<3 ) return false;
//存在A[i]是极值
let max = false;
for ( let i=1; i<A.length; i++ ) {
// A[i-1]< A[i] > A[i+1] 为极值
if ( A[i-1]< A[i] && A[i] > A[i+1] ) {
max = true;
continue;
}
// 有极值,非降序
if( max && (A[i] <= A[i+1] || A[i] >= A[i-1]) ) return false
// 无极值,非升序
if( !max && (A[i] >= A[i+1] || A[i] <= A[i-1]) ) return false
}
return max;
};
Runtime: 64 ms, faster than 74.61% of JavaScript online submissions for Valid Mountain Array.