Question:
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.
如果单调递增或单调递减,则数组是单调的。
如果对于所有i <j,a[i] <=a[j],数组A是单调递增的。如果对于所有i <j,a[i]>a[j],数组A是单调递减的。
当且仅当给定数组A为单调时返回真。
Example:
Input: [1,2,2,3]
Output: true
Input: [6,5,4,4]
Output: true
Input: [1,3,2]
Output: false
Input: [1,2,4,5]
Output: true
Input: [1,1,1]
Output: true
Solution:
/**
* @param {number[]} A
* @return {boolean}
*/
var isMonotonic = function(A) {
var arr = [];
for (var i = 0 ; i< A.length ; i ++) {
arr.push(A[i+1] - A[i]);
}
return !arr.some(i=>i>0) || !arr.some(i=>i<0)
};
good solutions:
var isMonotonic = function(A) {
let increase = true, decrease = true;
for(let i = 0; i < A.length - 1; i++) {
if(A[i] > A[i + 1]) increase = false;
if(A[i] < A[i + 1]) decrease = false;
}
return increase || decrease;
};