Given an array of integers nums
and an integer limit
, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit
.
Example 1:
Input: nums = [8,2,4,7], limit = 4 Output: 2 Explanation: All subarrays are: [8] with maximum absolute diff |8-8| = 0 <= 4. [8,2] with maximum absolute diff |8-2| = 6 > 4. [8,2,4] with maximum absolute diff |8-2| = 6 > 4. [8,2,4,7] with maximum absolute diff |8-2| = 6 > 4. [2] with maximum absolute diff |2-2| = 0 <= 4. [2,4] with maximum absolute diff |2-4| = 2 <= 4. [2,4,7] with maximum absolute diff |2-7| = 5 > 4. [4] with maximum absolute diff |4-4| = 0 <= 4. [4,7] with maximum absolute diff |4-7| = 3 <= 4. [7] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2.
Example 2:
Input: nums = [10,1,2,4,7,2], limit = 5 Output: 4 Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.
思路:求任意两个值的相差绝对值<limit,也就是最大值和最小值的相差< limit,维护区间最大和最小,那么就是deque,滑动窗口了,注意这题写j move,shrink i,比较好写; array里面存的是index;O(N).
class Solution {
public int longestSubarray(int[] nums, int limit) {
Deque<Integer> maxDeque = new LinkedList<>();
Deque<Integer> minDeque = new LinkedList<>();
int res = 0;
int i = 0;
for(int j = 0; j < nums.length; j++) {
// move j;
while(!maxDeque.isEmpty() && nums[maxDeque.peekLast()] < nums[j]) {
maxDeque.pollLast();
}
maxDeque.addLast(j);
while(!minDeque.isEmpty() && nums[j] < nums[minDeque.peekLast()]) {
minDeque.pollLast();
}
minDeque.addLast(j);
// move i;
while(nums[maxDeque.peekFirst()] - nums[minDeque.peekFirst()] > limit) {
if(nums[maxDeque.peekFirst()] == nums[i]) {
maxDeque.pollFirst();
}
if(nums[minDeque.peekFirst()] == nums[i]) {
minDeque.pollFirst();
}
i++; // shrink i;
}
// update res;
res = Math.max(res, j - i + 1);
}
return res;
}
}