给你一个整数数组 nums
,和一个表示限制的整数 limit
,请你返回最长连续子数组的长度,该子数组中的任意两个元素之间的绝对差必须小于或者等于 limit
。
如果不存在满足条件的子数组,则返回 0
。
示例 1:
输入:nums = [8,2,4,7], limit = 4 输出:2 解释:所有子数组如下: [8] 最大绝对差 |8-8| = 0 <= 4. [8,2] 最大绝对差 |8-2| = 6 > 4. [8,2,4] 最大绝对差 |8-2| = 6 > 4. [8,2,4,7] 最大绝对差 |8-2| = 6 > 4. [2] 最大绝对差 |2-2| = 0 <= 4. [2,4] 最大绝对差 |2-4| = 2 <= 4. [2,4,7] 最大绝对差 |2-7| = 5 > 4. [4] 最大绝对差 |4-4| = 0 <= 4. [4,7] 最大绝对差 |4-7| = 3 <= 4. [7] 最大绝对差 |7-7| = 0 <= 4. 因此,满足题意的最长子数组的长度为 2 。
示例 2:
输入:nums = [10,1,2,4,7,2], limit = 5 输出:4 解释:满足题意的最长子数组是 [2,4,7,2],其最大绝对差 |2-7| = 5 <= 5 。
示例 3:
输入:nums = [4,2,2,2,4,4,2,2], limit = 0 输出:3
提示:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
0 <= limit <= 10^9
提示 1
Use a sliding window approach keeping the maximum and minimum value using a data structure like a multiset from STL in C++.
提示 2
More specifically, use the two pointer technique, moving the right pointer as far as possible to the right until the subarray is not valid (maxValue - minValue > limit), then moving the left pointer until the subarray is valid again (maxValue - minValue <= limit). Keep repeating this process.
解法1:滑动窗口 + 有序集合
import com.sun.source.tree.Tree;
class Solution {
public int longestSubarray(int[] nums, int limit) {
int ans = Integer.MIN_VALUE;
TreeMap<Integer, Integer> window = new TreeMap<>();
int left = 0;
int right = 0;
while (right < nums.length) {
window.merge(nums[right], 1, Integer::sum);
while (window.lastKey() - window.firstKey()> limit) {
if (window.merge(nums[left], -1, Integer::sum) == 0) {
window.remove(nums[left]);
}
left++;
}
ans = Math.max(ans, right - left + 1);
right++;
}
return ans;
}
}
复杂度分析
- 时间复杂度:O(n logn),n 是 数组 nums 的长度。向有序集合中添加或删除元素都是 O(logn) 的时间复杂度。每个元素最多被添加与删除一次。
- 空间复杂度:O(n)。其中 n 是数组长度。最坏情况下有序集合将和原数组等大。
解法2:滑动窗口 + 单调队列
在解法1中,我们仅需要统计当前窗口内的最大值与最小值,因此我们也可以分别使用两个单调队列解决本题。
在实际代码中,我们使用一个单调递增的队列 queMin 维护最小值,一个单调递减的队列 queMax 维护最大值。这样我们只需要计算两个队列的队首的差值,即可知道当前窗口是否满足条件。
class Solution {
public int longestSubarray(int[] nums, int limit) {
int ans = Integer.MIN_VALUE;
// 从大到小,peekFirst()是最大的元素
Deque<Integer> queMax = new LinkedList<>();
// 从小到大,peekFirst()是最小的元素
Deque<Integer> queMin = new LinkedList<>();
int left = 0;
int right = 0;
while (right < nums.length) {
// 找到nums[right]在queMax中的位置
while (!queMax.isEmpty() && queMax.peekLast() < nums[right]) {
queMax.pollLast();
}
// 找到nums[right]在queMin中的位置
while (!queMin.isEmpty() && queMin.peekLast() > nums[right]) {
queMin.pollLast();
}
queMax.offerLast(nums[right]);
queMin.offerLast(nums[right]);
while (!queMax.isEmpty() && !queMin.isEmpty() && queMax.peekFirst() - queMin.peekFirst() > limit) {
if (nums[left] == queMax.peekFirst()) {
queMax.pollFirst();
}
if (nums[left] == queMin.peekFirst()) {
queMin.pollFirst();
}
left++;
}
ans = Math.max(ans, right - left + 1);
right++;
}
return ans;
}
}
复杂度分析
- 时间复杂度:O(n),n 是 数组 nums 的长度。我们最多遍历该数组两次,两个单调队列入队出队次数也均为 O(n)。
- 空间复杂度:O(n)。其中 n 是数组长度。最坏情况下单调队列将和原数组等大。