算法:滑动窗口的最大值
滑动窗口的最大值
滑动窗口的最大值
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
例如,如果输入数组{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]}。
分析
使用最大堆存储当前窗口的数据, 则此时堆顶元素即为当前窗口最大值;
滑动窗口时不断的移除窗口左端的元素(保证堆中元素和窗口相同)
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Queue;
public class Solution { public ArrayList<Integer> maxInWindows(int[] num, int size) { if (num == null || num.length == 0 || size <= 0) return new ArrayList<>(); Queue<Integer> queue = new PriorityQueue<>((x, y) -> y - x); int len = num.length; ArrayList<Integer> res = new ArrayList<>(len);
for (int i = 0; i < len; ++i) { queue.offer(num[i]); if (queue.size() < size) { continue; } res.add(queue.peek()); queue.remove(num[i - size + 1]); } return res; } }
|