239. Sliding Window Maximum
2016-04-25 11:49
295 查看
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 =
Therefore, return the max sliding window as
Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
Similar:
76. Minimum Window Substring
155. Min Stack
159. Longest Substring with At Most Two Distinct Characters
265. Paint House II
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.
Follow up:
Could you solve it in linear time?
Similar:
76. Minimum Window Substring
155. Min Stack
159. Longest Substring with At Most Two Distinct Characters
265. Paint House II
Solution 1. Priority Queue public class Solution { class Pair implements Comparable<Pair>{ public int key; public int idx; public Pair(int k, int id) { this.key = k; this.idx = id; } @Override public int compareTo(Pair p) { return this.key < p.key ? 1 : (this.key == p.key ? 0 : -1); // reverse order, from Large to Small } } public int[] maxSlidingWindow(int[] nums, int k) { if (nums.length == 0 || k <= 0) return new int[0]; PriorityQueue<Pair> que = new PriorityQueue<Pair>(); int[] ret = new int[nums.length - k + 1]; int i = 0; for (i = 0; i < nums.length; i++) { que.add(new Pair(nums[i], i)); while (que.peek().idx < i - k + 1) { que.poll(); } if (i >= k-1) { ret[i-k+1] = que.peek().key; } } return ret; } }
相关文章推荐
- 延迟调用
- js 页面操作cookie
- 最详细的Log4j使用教程
- 工具类-Uri转绝对路径
- JNI中JAVA调用C/C++方法
- Android View.post(Runnable )
- Android学习之 图解调用invalidate()和requestLayout()的过程
- linux下u盘的挂载
- 查看端口被哪个程序占用
- [BZOJ2296]随机种子
- 子页面是父页面通过window.open弹出
- selenium学习笔记(简单的元素定位)
- 百度地图&&覆盖物OverlayOptions
- 手写代码UI,xib和StoryBoard间的的优劣比较
- 浅谈协方差矩阵
- 机器学习值决策树算法(上)-ID3实现
- UE4 蓝图 实现 数组的边遍历边删除
- linux sed 命令详解
- ElasticSearch教程(二)——ElasticSearch基本插件head
- ElasticSearch教程(二)——ElasticSearch基本插件head