896. 单调数列
896. 单调数列
题目
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
Given an integer array nums, return true if the given array is monotonic, orfalse otherwise.
Example 1:
Input: nums = [1,2,2,3]
Output: true
Example 2:
Input: nums = [6,5,4,4]
Output: true
Example 3:
Input: nums = [1,3,2]
Output: false
Constraints:
1 <= nums.length <= 10^5-10^5 <= nums[i] <= 10^5
题目大意
如果数组是单调递增或单调递减的,那么它是 单调 的 。
如果对于所有 i <= j,nums[i] <= nums[j],那么数组 nums 是单调递增的。 如果对于所有 i <= j,nums[i]> = nums[j],那么数组 nums 是单调递减的。
当给定的数组 nums 是单调数组时返回 true,否则返回 false。
示例 1:
输入: nums = [1,2,2,3]
输出: true
示例 2:
输入: nums = [6,5,4,4]
输出: true
示例 3:
输入: nums = [1,3,2]
输出: false
提示:
1 <= nums.length <= 10^5-10^5 <= nums[i] <= 10^5
解题思路
标记递增和递减:
- 定义两个布尔变量
isIncreasing和isDecreasing。
- 定义两个布尔变量
遍历数组:
- 遍历数组中的每一对相邻元素,分别检查它们是否满足单调递增或单调递减。
- 如果数组中的有一对相邻元素满足
nums[i] > nums[i+1],则数组不满足递增条件,将isIncreasing设置为false。 - 如果数组中的有一对相邻元素满足
nums[i] < nums[i+1],则数组不满足递减条件,将isDecreasing设置为false。 - 如果
isDecreasing和isIncreasing都为false,则提前终止循环。
结果判断:
- 如果数组既不是递增的,也不是递减的(两个标志都为
false),直接返回false。 - 否则返回
true。
- 如果数组既不是递增的,也不是递减的(两个标志都为
复杂度分析
- 时间复杂度:
O(n),其中n是数组的长度,只需一次遍历。 - 空间复杂度:
O(1),只使用了常量空间(两个布尔变量)。
代码
/**
* @param {number[]} nums
* @return {boolean}
*/
var isMonotonic = function (nums) {
let isIncreasing = true;
let isDecreasing = true;
for (let i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
isDecreasing = false; // 违反递减性
}
if (nums[i] < nums[i - 1]) {
isIncreasing = false; // 违反递增性
}
if (!isIncreasing && !isDecreasing) {
break;
}
}
return isIncreasing || isDecreasing;
};
相关题目
| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 2210 | 统计数组中峰和谷的数量 | [✓] | 数组 | 🟢 | 🀄️ 🔗 |
| 3250 | 单调数组对的数目 I | 数组 数学 动态规划 2+ | 🔴 | 🀄️ 🔗 |
