896. Monotone Sequence
If the array is monotonically increasing or monotonically decreasing, then it is monotonic.
If for all i <= j, A[i] <= A[j], then the array A is monotonically increasing. If for all i <= j, A[i]> = A[j], then the array A is monotonically decreasing.
It returns true when the given array A is a monotonic array, otherwise it returns false.
Example 1:
Input: [1,2,2,3]
Output: true
Example 2:
Input: [6,5,4,4]
Output: true
Example 3:
Input: [1,3,2]
Output: false
Example 4:
Input: [1,2,4,5]
Output: true
Example 5:
Input: [1,1,1]
Output: true
prompt:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
// 方法一
public boolean isMonotonic(int[] A) {
int n=A.length;
boolean inc=true,dec=true;
for (int i=0;i<n-1;i++) {
if (A[i]>A[i+1]) {
inc = false;
}
if (A[i]<A[i+1]) {
dec = false;
}
}
return dec||inc;
}
// 方法二
public boolean isSorted(int[] A,boolean inc) {
int n = A.length;
if (inc) {
for (int i=0; i<n-1; i++) {
if(A[i]>A[i+1]) {
return false;
}
}
}else {
for (int i=0; i<n-1; i++) {
if(A[i]<A[i+1]) {
return false;
}
}
}
return true;
}
public boolean isMonotonic(int[] A) {
return isSorted(A,true) || isSorted(A,false);
}