/* * 239. Sliding Window Maximum * 2016-6-18 by Mingyang * 这里面我有两个误区: * 1.以为是找三个和最大的,其实只是找的是k个值中最大的保存下来 * 2.只能够看到这k个数,不能看到其他的数 * You can only see the k numbers in the window. * 这样的话用heap,也就是priority queue来说就比较好实现了 */ //这是priority queue的n的算法,就是不断地remove掉窗口外的数,不断地移动窗口 public static int[] maxSlidingWindow1(int[] nums, int k) { int len = nums.length; int[] result = new int[len - k + 1]; if (nums.length == 0) return new int[0]; Queue<Integer> queue = new PriorityQueue<Integer>(k, new Comparator<Integer>() { @Override public int compare(Integer i1, Integer i2) { return i2 - i1; } }); for (int i = 0; i < k; i++) { queue.add(nums[i]); } result[0] = queue.peek(); for (int i = k; i < len; i++) { queue.remove(nums[i - k]); queue.add(nums[i]); result[i - k + 1] = queue.peek(); } return result; } //这个就是比较挫的写法,两个for循环,就是n的平方,这样的话对后面的代码不好,不用每次都加完,只用存起来就好了 public static int[] maxSlidingWindow2(int[] nums, int k) { int[] res = new int[nums.length - k + 1]; if (k > nums.length) return res; PriorityQueue<Integer> maxHeap; int start = 0; while (start <= nums.length - k) { maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { return i2 - i1; } }); for (int i = start; i < nums.length && i < start + k; i++) { maxHeap.add(nums[i]); } res[start] = maxHeap.poll(); start++; } return res; }