LeetCode知识点总结 - 941
作者:互联网
LeetCode 941. Valid Mountain Array
考点 | 难度 |
---|---|
Array | Easy |
题目
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:
arr.length >= 3
- There exists some i with
0 < i < arr.length - 1
such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
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