描述
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.
分析
两次循环,判断列表是递增或递减。
解决方案1(Java)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public boolean isMonotonic(int[] A) { return isIncrease(A) || isDecrease(A); } public boolean isIncrease(int [] A) { for (int i = 0; i < A.length - 1; i++) { if (A[i+1] < A[i]) { return false; } } return true; } public boolean isDecrease(int [] A) { for (int i = 0; i < A.length - 1; i++) { if (A[i+1] > A[i]) { return false; } } return true; } }
|