其他分享
首页 > 其他分享> > LeetCode知识点总结 - 941

LeetCode知识点总结 - 941

作者:互联网

LeetCode 941. Valid Mountain Array

考点难度
ArrayEasy
题目

Given an array of integers arr, return true if and only if it is a valid mountain array.

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

  1. arr.length >= 3
  2. There exists some i with 0 < i < arr.length - 1 such that:
  3. arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
  4. arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
思路

先找到peak,检查peak是不是在第一位,再检查peak之后是不是递减的。

答案
public boolean validMountainArray(int[] A) {
        int N = A.length;
        int i = 0;

        // walk up
        while (i+1 < N && A[i] < A[i+1])
            i++;

        // peak can't be first or last
        if (i == 0 || i == N-1)
            return false;

        // walk down
        while (i+1 < N && A[i] > A[i+1])
            i++;

        return i == N-1;
    }

标签:知识点,arr,return,int,941,length,peak,array,LeetCode
来源: https://blog.csdn.net/m0_59773145/article/details/122632776