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.
檢查陣列是否為遞增或遞減陣列,可接受相同元素,若陣列中同時出現遞增與遞減情況,即無法通過驗證。
Input: nums = [1,2,2,3]
Output: true
Input: nums = [6,5,4,4]
Output: true
Input: nums = [1,3,2]
Output: false
Input: nums = [1,2,4,5]
Output: true
Input: nums = [1,1,1]
Output: true
宣告變數,up
、down
,若出現遞增,則down = 0
,出現遞減up = 0
,如果最終down = 0
與up = 0
,表示無法通過驗證。
var isMonotonic = function (A) {
let up = 1;
let down = 1;
for (let i = 1; i < A.length; i++) {
if (A[i] > A[i - 1]) {
down = 0;
} else if (A[i] < A[i - 1]) {
up = 0;
}
};
return (down || up);
};