Given an integer array nums, a sliding window of size k moves from the leftmost side of the array to the rightmost side of the array. You can only see the k numbers in the sliding window. The sliding window only moves one position to the right at a time.
Returns the maximum value in the sliding window.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
The maximum position of the sliding window
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Example 2:
Input: nums = [1], k = 1
Output: [1]
Example 3:
Input: nums = [1,-1], k = 1
Output: [1,-1]
Example 4:
Input: nums = [9,11], k = 2
Output: [11]
Example 5:
Input: nums = [4,-2], k = 2
Output: [4]
prompt:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
Source: LeetCode
Link: https://leetcode-cn.com/problems/sliding-window-maximum
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Idea: Too bad, not data structure but violence. The violent ones will not be posted, and the official ones will be posted.
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(k==1)
return nums;
int n = nums.length;
PriorityQueue<int[]> pq = new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] pair1, int[] pair2) {
return pair1[0] != pair2[0] ? pair2[0] - pair1[0] : pair2[1] - pair1[1];
}
});
//先只添加前k个
for (int i = 0; i < k; ++i) {
pq.offer(new int[]{
nums[i], i});
}
int[] ans = new int[n - k + 1];
ans[0] = pq.peek()[0];
System.out.println(ans[0]);
for (int i = k; i < n; ++i) {
pq.offer(new int[]{
nums[i], i});
//这一步很妙,只看最大值,如果你的最大值不在这个滑动窗口之中,那么就抛出
//不是最大值肯定就不在顶端,我不管你,有你没你都不影响
while (pq.peek()[1] <= i - k) {
pq.poll();
}
ans[i - k + 1] = pq.peek()[0];
}
return ans;
}
}