LeetCode 239 Sliding Window Maximum
2015-08-06 19:16
369 查看
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.
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
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
Therefore, return the max sliding window as [3,3,5,5,6,7].
Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array’s size for non-empty array.
这道题目,需要使用Java优先级队列来实现(堆)。
AP代码如下:
ps:有一个技巧,可以不自定义compatator():将数组中各元素的负值加入到优先级队列中,然后在返回的时候,将队列中元素的负值加入到结果数组中。
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
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
Therefore, return the max sliding window as [3,3,5,5,6,7].
Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array’s size for non-empty array.
这道题目,需要使用Java优先级队列来实现(堆)。
AP代码如下:
ps:有一个技巧,可以不自定义compatator():将数组中各元素的负值加入到优先级队列中,然后在返回的时候,将队列中元素的负值加入到结果数组中。
public class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if(k==0) return nums; int len = nums.length; int[] rst = new int[len - k + 1]; PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(k, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { // TODO Auto-generated method stub return o1 < o2 ? 1 : (o1 > o2 ? -1 : 0); } }); for (int i = 0; i < k - 1; i++) { priorityQueue.offer(nums[i]); } for (int i = 0; i < len - k + 1; i++) { priorityQueue.offer(nums[i + k - 1]); rst[i] = priorityQueue.peek(); priorityQueue.remove(nums[i]); } return rst; } }
相关文章推荐
- Android onconfiguration属性
- hdu 3336 Count the string(kmp应用)
- c++类实现基本的6种排序算法
- hdu 4750——Count The Pairs
- Android 圆形滚动菜单
- —软测试—(5)计算机系统CPU组成
- Nginx: could not build the server_names_hash 解决办法
- poj3301--Texas Trip(最小正方形覆盖)
- MySQL IN用法
- 【费用流】 HDOJ 5352 MZL's City
- Linux 下 安装Mysql
- 听课练习(四)
- 《乌合之众》思维导图及优秀读后感
- sql关于Group by
- 欧拉通路-Play on Words
- 解决NDK开发中Eclipse报错“Unresolved inclusion jni.h”的最终方法
- 欧拉通路-Play on Words 分类: POJ 图论 2015-08-06 19:13 4人阅读 评论(0) 收藏
- ASP.NET CSS 小结
- C#高级编程七十五天----C#使用指针
- iOS 设置导航栏的主题