Description:
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
题意:判断数组A是否存在小标 i i i,使得 A [ 0 ] < A [ 1 ] < . . . A [ i − 1 ] < A [ i ] A[0] < A[1] < ... A[i-1] < A[i] A[0]<A[1]<...A[i−1]<A[i]且 A [ i ] > A [ i + 1 ] > . . . > A [ B . l e n g t h − 1 ] A[i] > A[i+1] > ... > A[B.length - 1] A[i]>A[i+1]>...>A[B.length−1];并且 A A A的长度大于或等于3, 0 < i < A . l e n g t h − 1 0 < i < A.length - 1 0<i<A.length−1;
解法:我们只要分别从首尾遍历,找到第一个不满足大小关系的位置后,判断这两个位置是否相同即可,具体流程如下
- for st in [0, A.length - 1)
- until A[st] > A[st + 1]
- for ed in [A.length - 1, 1]
- until A[ed] > A[ed - 1]
- 比较st与ed是否相同,并且满足st与ed的位置在(0, A.length - 1)
Java
class Solution {
public boolean validMountainArray(int[] A) {
if (A.length < 3) {
return false;
}
int st = 0;
int ed = A.length - 1;
while (st < A.length - 1 && A[st] < A[st + 1]) {
st++;
}
while (ed > 0 && A[ed] < A[ed - 1]) {
ed--;
}
return st == ed && st != 0 && st != A.length - 1 ? true : false;
}
}