An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Output: true
Example 5:
Input: [1,1,1]
Output: true
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
判断一个数组是否是单调数组,单调是指元素为单调上升或单调下降,单调上升指A[i] <= A[ I+1 ], 单调下降指A[i ] >= A[ i+1 ]
思路:
单调只有一个方向,要么上升要么下降,先确定这个方向。
定义变量larger = -1,-1表示还未确定方向,然后一旦遇到A[i] < A[i +1],确定单调上升,larger=0, 这之后遇到A[i] > A[i+1]时表示出现矛盾,返回false
单调下降时同理
A[i] == A[i+1]对两个方向都适用,不做判断。
如果没有矛盾的情况出现,最后返回true
public boolean isMonotonic(int[] A) {
int n = A.length;
if(n <= 2) return true;
int larger = -1;
for(int i = 0; i < n-1; i++) {
if(larger == -1) {
if(A[i] < A[i+1]) {
larger = 0;
} else if(A[i] > A[i+1]) {
larger = 1;
}
} else if (larger == 0) {
if(A[i] > A[i+1]) return false;
} else {
if(A[i] < A[i+1]) return false;
}
}
return true;
}