LeetCode 3105. Longest Strictly Increasing or Strictly Decreasing Subarray
3105. Longest Strictly Increasing or Strictly Decreasing Subarray
You are given an array of integers nums
. Return the
length of the longest subarray of nums which is either strictly
increasing or strictly decreasing.
解题思路
- 遍历数组:我们需要遍历
nums
数组,找到最长的严格递增或严格递减子数组的长度。 - 使用两个计数器:
inc_len
记录当前递增子数组的长度。dec_len
记录当前递减子数组的长度。
- 更新逻辑:
- 如果
nums[i] > nums[i - 1]
,说明递增,递增计数器inc_len
增加,并重置递减计数器dec_len
。 - 如果
nums[i] < nums[i - 1]
,说明递减,递减计数器dec_len
增加,并重置递增计数器inc_len
。 - 如果相等,则重置两个计数器为 1。
- 如果
- 维护最大值:在每一步更新
max_len
,确保获取最长的子数组长度。
代码实现 (Python)
1 | def longest_strictly_increasing_or_decreasing_subarray(nums): |
时间复杂度分析
- 遍历一次数组,时间复杂度为
O(n),其中
n
是nums
的长度。
示例
1 | print(longest_strictly_increasing_or_decreasing_subarray([1, 2, 3, 4, 3, 2, 1])) # 输出: 7 |
总结
- 维护两个变量
inc_len
和dec_len
,在遍历过程中更新长度。 - 只需 O(n) 的时间复杂度即可求解。
- 适用于 任意整数数组,不会受到数值范围的影响。
这种方法简单且高效,适用于大规模数据集。🚀