941. 有效的山脉数组
941. Valid Mountain Array
题目描述
给定一个整数数组 A,如果它是有效的山脉数组就返回 true,否则返回 false。
让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组:
- A.length >= 3
- 在 0 < i < A.length - 1 条件下,存在 i 使得:
- A[0] < A[1] < ... A[i-1] < A[i]
- A[i] > A[i+1] > ... > A[B.length - 1]
LeetCode941. Valid Mountain Array
示例 1:
输入: [2,1]
输出: false
示例 2:
输入: [3,5,5]
输出: false
示例 3:
输入: [0,3,2,1]
输出: true
提示:
- 0 <= A.length <= 10000
- 0 <= A[i] <= 10000
Java 实现
class Solution {
public boolean validMountainArray(int[] A) {
if (A == null || A.length < 3) {
return false;
}
int n = A.length;
int low = 0, high = n - 1;
while (low < high && A[low] < A[low + 1]) {
low++;
}
while (low < high && A[high] < A[high - 1]) {
high--;
}
if (low == n - 1 || high == 0) {
return false;
}
return low == high ? true : false;
}
}
参考资料
- https://leetcode.com/problems/valid-mountain-array/
- https://leetcode-cn.com/problems/valid-mountain-array/
原文地址:https://www.cnblogs.com/hglibin/p/10920674.html
时间: 2024-11-02 19:11:14