896. Monotonic Array
Problem
判断一个数组是否为单调不减或单调不增数组。
i <= j ,A[i] <= A[j]
或
i >= j , A[i] >= A[j]
Example
Input: [1,2,2,3]
Output: trueInput: [6,5,4,4]
Output: trueInput: [1,3,2]
Output: falseInput: [1,2,4,5]
Output: trueInput: [1,1,1]
Output: true
Solution
class Solution {
public boolean isMonotonic(int[] A) {
if (A.length < 3) return true;
boolean isInc = false, isDesc = false;//初始化为false
for (int i = 0, L = A.length - 1; i < L; i++) {
if (A[i] < A[i + 1] && !isInc) {//假如为增长趋势,认为序列是递增的(&&了!isInc只是为了提高效率,以后不再进来重复设值)
isInc = true;
} else if (A[i] > A[i + 1] && !isDesc) {//假如出现下降趋势,认为序列是递减的
isDesc = true;
}
if (isInc && isDesc) return false;//如果都为true,既是递增也是递减,出现矛盾,return false;
}
return true;
}
}