简介

滑动窗口, 使用优点队列, 即大小堆来实现

code

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        PriorityQueue<int[]> pq = new PriorityQueue<int []>(new Comparator<int[]>() {
            public int compare(int[] pair1, int [] pair2) {
                return pair1[0] != pair2[0] ? pair2[0] - pair1[0] : pair2[1] - pair1[1];
            }// 新的构造函数参数, 
        });
        for(int i = 0; i<k; i++){
            pq.offer(new int[]{nums[i], i});
        }
        int[] ans = new int[n - k + 1];
        ans[0] = pq.peek()[0]; // peek == top
        for(int i=k; i<n; i++){
            pq.offer(new int[] {nums[i], i});
            while(pq.peek()[1] <= i - k){
                pq.poll();
            }
            ans[i - k + 1] = pq.peek()[0];
        }
        return ans;
    }
}
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        int n = nums.size();
        priority_queue<pair<int, int>> q;
        for(int i = 0; i<k; ++i){
            q.emplace(nums[i], i); // 记住是emplace 而不是  emplace_back
        }
        vector<int> ans = {q.top().first};
        for(int i = k; i<n; i++){
            q.emplace(nums[i], i);
            while(q.top().second <= i - k) {
                q.pop();
            }
            ans.push_back(q.top().first);
        }
        return ans;
    }
};
posted on 2021-06-03 08:46  HDU李少帅  阅读(41)  评论(0编辑  收藏  举报