941. Valid Mountain Array*
https://leetcode.com/problems/valid-mountain-array/
题目描述
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 somei
with0 < i < A.length - 1
such that:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[A.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
C++ 实现 1
我的实现比较复杂, 放在 C++ 实现 2
中进行介绍. 这里的实现来自 LeetCode 的 Submission.
思路是左右开弓, 只要判断最后两个指针是否重合并且不指向数组的两端.
class Solution
{
public:
bool validMountainArray(vector<int>& A)
{
if(A.size()<=2)return false;
int left=0;
int right=A.size()-1;
while(left<A.size()-1&&A[left]<A[left+1])
{
left++;
}
while(right>0&&A[right]<A[right-1])
{
right--;
}
return left==right&&left!=A.size()-1&&right!=0;
}
};
C++ 实现 2
beats 86%
. 思路是用 isIncreasing
以及 isDecreasing
来标识数组的状态. 数组处于上升阶段就设置 isIncreasing = true
, 数组处于下降阶段就设置 isDecreasing = true
.
如果:
A[i] > A[i - 1]
, 即此时数组处于上升阶段, 若此时isDecreasing = true
, 说明上升不连续, 返回 false.A[i] < A[i - 1]
, 即此时数组处于下降阶段, 如果此时isIncreasing = true
, 说明下降不连续, 返回 false.- 然而, 还需要考虑的是, 如果是单调序列, 比如单调递减序列那该咋办. 因此引入
count_inc
来记录上升阶段的大小, 如果最后其值为0
, 说明数组没有经历过上升阶段, 无疑是递减序列, 返回 false.
算了, 不分析了, 没有必要记录这种复杂的方法, 不优雅.
class Solution {
public:
bool validMountainArray(vector<int>& A) {
if (A.size() < 3) return false;
bool isIncreasing = false, isDecreasing = false;
int count_inc = 0, count_dec = 0;
for (int i = 1; i < A.size(); ++ i) {
if (A[i] == A[i - 1]) return false;
if (A[i] > A[i - 1]) {
if (isDecreasing) return false;
isIncreasing = true;
count_inc += 1;
}
if (A[i] < A[i - 1]) {
if (count_inc == 0) return false; // 处理单调递减序列
if (count_dec == 0) {
count_dec ++;
isIncreasing = false;
}
if (isIncreasing) return false;
isDecreasing = true;
}
}
if (!isIncreasing && isDecreasing) return true;
return false; // 介绍上一个 if 的条件, 可以处理单调递增序列
}
};