-
溫馨 小提示:如果代碼看不懂,不妨拿出紙和筆,找幾個例子,多走幾遍程序,
再搜索一下相關的博客,慢慢的就加深理解了。
題目:
給定一個數組和滑動窗口的大小,找出所有滑動窗口裏數值的最大值。例如,如果輸入數組{2,3,4,2,6,2,5,1}及滑動窗口的大小3,那麼一共存在6個滑動窗口,他們的最大值分別爲{4,4,6,6,6,5}; 針對數組{2,3,4,2,6,2,5,1}的滑動窗口有以下6個: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
代碼思路:
法一:簡單的暴力法
法二:雙向隊列
用一個雙向隊列,隊列第一個位置保存當前窗口的最大值,當窗口滑動一次,判斷當前最大值是否過期(當前最大值的位置是不是在窗口之外),新增加的值從隊尾開始比較,把所有比他小的值丟掉。這樣時間複雜度爲O(n)。
解題代碼:
法一:簡單的暴力法
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> res = new ArrayList<Integer>();
if(num.length < size || size == 0)
return res;
for(int i = 0; i < num.length - size + 1; i++){
res.add(max(num, i, size));
}
return res;
}
public int max(int [] num, int index, int size){
int res = num[index];
for(int i = index + 1; i < index + size; i++){
if(num[i] > res)
res = num[i];
}
return res;
}
}
法二:雙向隊列
import java.util.ArrayList;
import java.util.LinkedList;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size){
ArrayList<Integer> res = new ArrayList<Integer>();
LinkedList<Integer> deque = new LinkedList<Integer>();
if(num.length == 0 || size == 0)
return res;
for(int i = 0; i < num.length; i++){
if(!deque.isEmpty() && deque.peekFirst() <= i - size)
deque.poll();
while(!deque.isEmpty() && num[deque.peekLast()] < num[i])
deque.removeLast();
deque.offerLast(i);
if(i + 1 >= size)
res.add(num[deque.peekFirst()]);
}
return res;
}
}
參考文章:
https://www.weiweiblog.cn/maxinwindows/