|
| 1 | +/** |
| 2 | + * An array is monotonic if it is either monotone increasing or monotone decreasing. |
| 3 | + * |
| 4 | + * An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is |
| 5 | + * monotone decreasing if for all i <= j, A[i] >= A[j]. |
| 6 | + * |
| 7 | + * Return true if and only if the given array A is monotonic. |
| 8 | + * |
| 9 | + * Example 1: |
| 10 | + * Input: [1,2,2,3] |
| 11 | + * Output: true |
| 12 | + * |
| 13 | + * Example 2: |
| 14 | + * Input: [6,5,4,4] |
| 15 | + * Output: true |
| 16 | + * |
| 17 | + * Example 3: |
| 18 | + * Input: [1,3,2] |
| 19 | + * Output: false |
| 20 | + * |
| 21 | + * Example 4: |
| 22 | + * Input: [1,2,4,5] |
| 23 | + * Output: true |
| 24 | + * |
| 25 | + * Example 5: |
| 26 | + * Input: [1,1,1] |
| 27 | + * Output: true |
| 28 | + * |
| 29 | + * Note: |
| 30 | + * 1 <= A.length <= 50000 |
| 31 | + * -100000 <= A[i] <= 100000 |
| 32 | + */ |
| 33 | + |
| 34 | +publicclassMonotonicArray896 { |
| 35 | +publicbooleanisMonotonic(int[]A) { |
| 36 | +if (A ==null ||A.length <=2)returntrue; |
| 37 | +inti =1; |
| 38 | +intlen =A.length; |
| 39 | +while (i <len &&A[i] ==A[i-1])i++; |
| 40 | +if (i ==len)returntrue; |
| 41 | +booleanflag =A[i] >A[i-1]; |
| 42 | +while (i <len) { |
| 43 | +if (A[i] !=A[i-1] &&flag !=A[i] >A[i-1])returnfalse; |
| 44 | +i++; |
| 45 | + } |
| 46 | +returntrue; |
| 47 | + } |
| 48 | + |
| 49 | +/** |
| 50 | + * https://leetcode.com/problems/monotonic-array/solution/ |
| 51 | + */ |
| 52 | +publicbooleanisMonotonic2(int[]A) { |
| 53 | +intstore =0; |
| 54 | +for (inti =0;i <A.length -1; ++i) { |
| 55 | +intc =Integer.compare(A[i],A[i+1]); |
| 56 | +if (c !=0) { |
| 57 | +if (c !=store &&store !=0) |
| 58 | +returnfalse; |
| 59 | +store =c; |
| 60 | + } |
| 61 | + } |
| 62 | +returntrue; |
| 63 | + } |
| 64 | +} |