Skip to content

Latest commit

 

History

History
136 lines (96 loc) · 3.92 KB

0896.md

File metadata and controls

136 lines (96 loc) · 3.92 KB
title description keywords
896. 单调数列
LeetCode 896. 单调数列题解,Monotonic Array,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
896. 单调数列
单调数列
Monotonic Array
解题思路
数组

896. 单调数列

🟢 Easy  🔖  数组  🔗 力扣 LeetCode

题目

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 <= jnums[i] <= nums[j],那么数组 nums 是单调递增的。 如果对于所有 i <= jnums[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

解题思路

  1. 标记递增和递减

    • 定义两个布尔变量 isIncreasingisDecreasing
  2. 遍历数组

    • 遍历数组中的每一对相邻元素,分别检查它们是否满足单调递增或单调递减。
    • 如果数组中的有一对相邻元素满足 nums[i] > nums[i+1],则数组不满足递增条件,将 isIncreasing 设置为 false
    • 如果数组中的有一对相邻元素满足 nums[i] < nums[i+1],则数组不满足递减条件,将 isDecreasing 设置为 false
    • 如果 isDecreasingisIncreasing 都为 false,则提前终止循环。
  3. 结果判断

    • 如果数组既不是递增的,也不是递减的(两个标志都为 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+ 🔴 🀄️ 🔗