239. Sliding Window Maximum
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[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
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
解法一:暴力法
//1. 遍历求出每个滑动窗口
//2. 在每个滑动窗口中求出最大值,记录下来。
//3. 注意边界情况的处理,如:输入的数组为null,或者为空;滑动窗口的大小为零,或者大于数组长度等。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> arr = new ArrayList<Integer>();
if(num==null || num.length==0 || size==0){
return arr;
}
int len=num.length, inx=0, end=len-1;
if(size>len){
return arr;
}else if(size==len){
arr.add(maxNum(num, 0, len-1));
}else{
for(int i=0; i<len; i++){
inx = i;
end = inx+size-1;
if(end >= len){
break;
}else{
arr.add(maxNum(num, inx, end));
}
}
}
return arr;
}
//求几个值中的最大值
public int maxNum(int[] num, int inx, int end){
int max = num[inx];
for(int i=inx; i<=end; i++){
if(num[i]>max){
max = num[i];
}
}
return max;
}
}
解法二:双端队列 大顶堆简化版 Max Heap
//1. 滑动窗口应当是队列,但为了得到滑动窗口的最大值,队列序可以从两端删除元素,因此使用双端队列。
//2. 对新来的元素k,将其与双端队列中的元素相比较, 前面比k小的,直接移出队列(因为不再可能成为后面滑动窗口的最大值了!
//3. 前面比k大的X,比较两者下标,判断X是否已不在窗口之内,不在了,直接移出队列。队列的第一个元素是当前滑动窗口中的最大值
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> res = new ArrayList<>();
if(size == 0) return res;
int begin;
ArrayDeque<Integer> q = new ArrayDeque<>();
for(int i = 0; i < num.length; i++){
begin = i - size + 1;
if(q.isEmpty())
q.add(i);
else if(begin > q.peekFirst())
q.pollFirst();
while((!q.isEmpty()) && num[q.peekLast()] <= num[i])
q.pollLast();
q.add(i);
if(begin >= 0)
res.add(num[q.peekFirst()]);
}
return res;
}