File tree
Expand file treeCollapse file tree1 file changed
+64
-0
lines changed Expand file treeCollapse file tree1 file changed
+64
-0
lines changed Original file line number | Diff line number | Diff line change |
---|
|
| 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 | +public class MonotonicArray896 { |
| 35 | +public boolean isMonotonic(int[] A) { |
| 36 | +if (A == null || A.length <= 2) return true; |
| 37 | +int i = 1; |
| 38 | +int len = A.length; |
| 39 | +while (i < len && A[i] == A[i-1]) i++; |
| 40 | +if (i == len) return true; |
| 41 | +boolean flag = A[i] > A[i-1]; |
| 42 | +while (i < len) { |
| 43 | +if (A[i] != A[i-1] && flag != A[i] > A[i-1]) return false; |
| 44 | +i++; |
| 45 | +} |
| 46 | +return true; |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | +* https://leetcode.com/problems/monotonic-array/solution/ |
| 51 | +*/ |
| 52 | +public boolean isMonotonic2(int[] A) { |
| 53 | +int store = 0; |
| 54 | +for (int i = 0; i < A.length - 1; ++i) { |
| 55 | +int c = Integer.compare(A[i], A[i+1]); |
| 56 | +if (c != 0) { |
| 57 | +if (c != store && store != 0) |
| 58 | +return false; |
| 59 | +store = c; |
| 60 | +} |
| 61 | +} |
| 62 | +return true; |
| 63 | +} |
| 64 | +} |
You can’t perform that action at this time.
0 commit comments