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 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]
  2. Output: false
  1. Input: [3,5,5]
  2. Output: false
  3. Input: [0,3,2,1]
  4. Output: true

Solution:

  1. /**
  2. * @param {number[]} A
  3. * @return {boolean}
  4. */
  5. var validMountainArray = function(A) {
  6. // 数组长度大于3
  7. if ( A.length<3 ) return false;
  8. //存在A[i]是极值
  9. let max = false;
  10. for ( let i=1; i<A.length; i++ ) {
  11. // A[i-1]< A[i] > A[i+1] 为极值
  12. if ( A[i-1]< A[i] && A[i] > A[i+1] ) {
  13. max = true;
  14. continue;
  15. }
  16. // 有极值,非降序
  17. if( max && (A[i] <= A[i+1] || A[i] >= A[i-1]) ) return false
  18. // 无极值,非升序
  19. if( !max && (A[i] >= A[i+1] || A[i] <= A[i-1]) ) return false
  20. }
  21. return max;
  22. };

Runtime: 64 ms, faster than 74.61% of JavaScript online submissions for Valid Mountain Array.