您的位置:首页 > 其它

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():将数组中各元素的负值加入到优先级队列中,然后在返回的时候,将队列中元素的负值加入到结果数组中。

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: