topic:
1438. The longest continuous subarray whose absolute difference does not exceed the limit
Given an integer array nums and an integer limit representing the limit, please return the length of the longest continuous sub-array. The absolute difference between any two elements in the sub-array must be less than or equal to limit.
If there is no sub-array that meets the condition, 0 is returned.
Example 1:
Input: nums = [8,2,4,7], limit = 4
Output: 2
Explanation: All sub-arrays are as follows:
[8] Maximum absolute difference |8-8| = 0 <= 4.
[8,2] Maximum Absolute difference |8-2| = 6> 4.
[8,2,4] Maximum absolute difference |8-2| = 6> 4.
[8,2,4,7] Maximum absolute difference |8-2| = 6> 4.
[2] Maximum absolute difference |2-2| = 0 <= 4.
[2,4] Maximum absolute difference |2-4| = 2 <= 4.
[2,4,7] Maximum absolute difference |2-7| = 5> 4.
[4] Maximum absolute difference |4-4| = 0 <= 4.
[4,7] Maximum absolute difference |4-7| = 3 <= 4.
[7] Maximum Absolute difference |7-7| = 0 <= 4.
Therefore, the length of the longest sub-array that satisfies the meaning of the question is 2.
Example 2:
Input: nums = [10,1,2,4,7,2], limit = 5
Output: 4
Explanation: The longest sub-array that satisfies the meaning of the question is [2,4,7,2], and its maximum absolute difference|2 -7| = 5 <= 5.
Example 3:
Input: nums = [4,2,2,2,4,4,2,2], limit = 0
Output: 3
prompt:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
0 <= limit <= 10^9
Problem solution ideas:
If you use a normal list to sort again, it will increase the time complexity of a logn, and it will time out!
After selecting the data type of the ordered list, you can directly set the sliding window template, which is simple. . .
Python sliding window template: https://blog.csdn.net/weixin_44414948/article/details/113862173
Problem solution python code:
class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
from sortedcontainers import SortedList
s = SortedList() # 使用有序列表数据类型
n = len(nums)
left = right = 0
ans = 0
while right<n:
s.add(nums[right]) # 注意有序列表类型没有append,只有add
while s[-1]-s[0]>limit: # 右指针移动至不满足limit时,开始移动左指针至满足条件
s.remove(nums[left])
left += 1 # 左指针移动
ans = max(ans, right-left+1) # 更新最大长度
right += 1
return ans
Author: a-qing-ge
Links: https://leetcode-cn.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/solution/hua-chuang -mo-ban-ti-xuan-ze-you-xu-lie-286dv/
Source: LeetCode https://leetcode-cn.com/problems/longest-continuous-subarray-with-absolute-diff- less-than-or-equal-to-limit/