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:

  1. Input: [1,2,2,3]
  2. Output: true
  3. Input: [6,5,4,4]
  4. Output: true
  5. Input: [1,3,2]
  6. Output: false
  7. Input: [1,2,4,5]
  8. Output: true
  9. Input: [1,1,1]
  10. Output: true

Solution:

  1. /**
  2. * @param {number[]} A
  3. * @return {boolean}
  4. */
  5. var isMonotonic = function(A) {
  6. var arr = [];
  7. for (var i = 0 ; i< A.length ; i ++) {
  8. arr.push(A[i+1] - A[i]);
  9. }
  10. return !arr.some(i=>i>0) || !arr.some(i=>i<0)
  11. };

good solutions:

  1. var isMonotonic = function(A) {
  2. let increase = true, decrease = true;
  3. for(let i = 0; i < A.length - 1; i++) {
  4. if(A[i] > A[i + 1]) increase = false;
  5. if(A[i] < A[i + 1]) decrease = false;
  6. }
  7. return increase || decrease;
  8. };