您的位置:首页 > 其它

leetcode239:Sliding Window Maximum

2015-07-19 16:00 316 查看
Given an array nums,there is a sliding window of size k whichis moving from the very left of the array to the very right. You can only see the k numbersin 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       31 [3  -1  -3] 5  3  6  7       31  3 [-1  -3  5] 3  6  7       51  3  -1 [-3  5  3] 6  7       51  3  -1  -3 [5  3  6] 7       61  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?思路;这里用了Java中的双队列数据结构 Deque(实现类中的ArrayDeque)
public static  int[] maxSlidingWindow(int[] nums,int k){if(k==0)  //不要忘记特殊情况return null;int[] results = new int[nums.length-k+1];Deque<Integer> deque = new ArrayDeque<Integer>(); //Integer不能用intint count = 0;for(int i=0;i<nums.length;i++){//deque中存储的元素:是当前窗口内的元素中的几个,且得保证队首是窗口中最大元素while(!deque.isEmpty() && nums[i]>deque.getLast())deque.pollLast();deque.add(nums[i]);if(i>=k-1){  //从第K-1个元素开始,窗口已满,先滑出,再滑入results[count++] = deque.getFirst();if(nums[i-k+1]==deque.getFirst()){deque.pollFirst();  //滑出的正好是窗口内元素最大的,deque弹出}}}return results;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: