renjie-run / blog

Personal Blog
2 stars 0 forks source link

[算法] - 单调数列 #27

Open renjie-run opened 3 years ago

renjie-run commented 3 years ago

难度等级:简单

如果数组是单调递增或单调递减的,那么它是单调的。

如果对于所有 i <= j,A[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= j,A[i]> = A[j],那么数组 A 是单调递减的。 当给定的数组 A 是单调数组时返回 true,否则返回 false。

示例 1:

输入:[1,2,2,3]
输出:true

示例 2:

输入:[6,5,4,4]
输出:true

示例 3:

输入:[1,3,2]
输出:false

示例 4:

输入:[1,2,4,5]
输出:true

示例 5:

输入:[1,1,1]
输出:true

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/monotonic-array

renjie-run commented 3 years ago

官方解法

/**
 * @param {number[]} A
 * @return {boolean}
 */
const isSorted = function(arr) {
    return arr.slice(1).every((item, index) => arr[index] <= item);
};

const isMonotonic = function(A) {
    const ALength = A.length;
    if (ALength < 1 || ALength > 50000) {
        return false;
    }
    if (ALength === 1 || ALength === 2) {
        return true;
    }
    return isSorted(A) || isSorted(A.reverse());
};
renjie-run commented 3 years ago

个人解法

/**
 * @param {number[]} A
 * @return {boolean}
 */
const isMonotonic = function(A) {
  const ALength = A.length;
  if (ALength < 1 || ALength > 50000) {
      return false;
  }
  if (ALength === 1 || ALength === 2) {
      return true;
  }
  let isMonotonic = true;
  let i = 0;
  let type = '';
  while(i < ALength) {
      if (i === ALength - 1) {
          break;
      }
      const currNum = A[i];
      const nextNum = A[i + 1];
      i++;
      if (currNum < nextNum) {
          if (!type) {
              type = 'increase';
          } else if (type === 'decrease') {
             isMonotonic = false;
             break;
          }
      } else if (currNum > nextNum) {
          if (!type) {
              type = 'decrease';
          } else if (type === 'increase') {
              isMonotonic = false;
              break;
          }
      }
  }
  return isMonotonic;
};