1. 程式人生 > >Monotonic Array

Monotonic Array

An array is monotonic if it is either monotone increasing or monotone decreasing.

An array A is monotone increasing if for all i <= jA[i] <= A[j].  An array A is monotone decreasing if for all i <= jA[i] >= A[j].

Return true if and only if the given array A is monotonic.

判斷一個數組是否有序,降序升序都可以。

思路:給一個標記來記當前的陣列排序方法,如果排序方法改變了,那麼就不是有序的陣列

public boolean isMonotonic(int[] A) {         int f=0;         for (int i = 0; i < A.length-1; i++) {             if(A[i]==A[i+1]){                 continue;             }else if(A[i]<A[i+1]){                 if( f == 0){                     f = 1;                 }else if(f==2){                     return false;                 }             }else if(A[i]>A[i+1]){                 if( f == 0){                     f = 2;                 }else if(f==1){                     return false;                 }             }         }         return true;     }