Open renjie-run opened 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());
};
个人解法
/**
* @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;
};
难度等级:简单
如果数组是单调递增或单调递减的,那么它是单调的。
如果对于所有 i <= j,A[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= j,A[i]> = A[j],那么数组 A 是单调递减的。 当给定的数组 A 是单调数组时返回 true,否则返回 false。
示例 1:
示例 2:
示例 3:
示例 4:
示例 5:
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/monotonic-array