LeetCode 题解工作台
单调数列
如果数组是单调递增或单调递减的,那么它是 单调 的 。 如果对于所有 i , nums[i] ,那么数组 nums 是单调递增的。 如果对于所有 i , nums[i] >= nums[j] ,那么数组 nums 是单调递减的。 当给定的数组 nums 是单调数组时返回 true ,否则返回 fal…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
遍历数组,如果出现递增或递减的情况,记录下来。判断是否出现过递增和递减的情况,如果都出现过,说明不是单调数组,返回 `false`。 否则遍历结束,说明是单调数组,返回 `true`。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
如果数组是单调递增或单调递减的,那么它是 单调 的。
如果对于所有 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 <= 105-105 <= nums[i] <= 105
解题思路
方法一:一次遍历
遍历数组,如果出现递增或递减的情况,记录下来。判断是否出现过递增和递减的情况,如果都出现过,说明不是单调数组,返回 false。
否则遍历结束,说明是单调数组,返回 true。
时间复杂度 ,其中 为数组长度。空间复杂度 。
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
asc = all(a <= b for a, b in pairwise(nums))
desc = all(a >= b for a, b in pairwise(nums))
return asc or desc
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each element is visited once in a linear scan. Space complexity is O(1) because only two flags are stored regardless of array size. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Watch for off-by-one errors when comparing adjacent elements in the array.
- question_mark
Check edge cases like arrays with all identical elements or a single element.
- question_mark
Be ready to explain why a linear pass is sufficient instead of nested loops.
常见陷阱
外企场景- error
Assuming strictly increasing or decreasing rather than non-strict comparisons.
- error
Forgetting to handle arrays with only one element correctly.
- error
Overcomplicating with extra data structures instead of simple flags.
进阶变体
外企场景- arrow_right_alt
Determine the longest monotonic prefix of an array.
- arrow_right_alt
Count the number of monotonic subarrays of length at least two.
- arrow_right_alt
Check monotonicity only for odd- or even-indexed elements.