第13天 Monotonic Queue and Heap 239、347

239. 滑动窗口最大值 

  • 根据题意,i为nums下标,是要在[i - k + 1, i] 中选到最大值,只需要保证两点
  • 1.队列头结点需要在[i - k + 1, i]范围内,不符合则要弹出队列开头
    • E.g. nums = [1,3,-1,-3,5,3,2,1] deque = [1,3,-1] 现在要更新下一个窗口,要把1去掉(1的index为0,i现在为3,3-0>=3),加-3
  • 2.既然是单调,就要保证每次放进去的数字要比末尾的都大,否则也弹出队列结尾
  • 因为单调,当i增长到符合第一个k范围的时候,每滑动一步都将队列头节点放入结果就行了

  • Time complexity : O(N), since each element is processed exactly twice - it's index added and then removed from the deque.

  • Space complexity : O(N), since O(N−k+1) is used for an output array and O(k) for a deque.

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        Deque<Integer> deque = new ArrayDeque<Integer>();
        int[] ans = new int[nums.length-k+1];
        for (int i=0; i<nums.length; i++) {
            int start = i-k+1;
            while (!deque.isEmpty() && i-deque.peekFirst()>=k) 
                deque.pollFirst();
            while (!deque.isEmpty() && nums[i]>nums[deque.peekLast()]) 
                deque.pollLast();
            deque.addLast(i);
            if (start >= 0) ans[start] = nums[deque.peekFirst()];
        }
        return ans;
    }
}

347.前 K 个高频元素

  • 方法1: 用小根堆,出现频率低的在前面
Queue<Integer> q = new PriorityQueue<> ((a,b)->map.get(a)-map.get(b));
  • heap.size()>=k 弹出最前面的(频率最少的)
  • Time complexity : O(Nlog⁡k) if k<N and O(N) in the particular case of N=k. That ensures time complexity to be better than O(Nlog⁡N).

  • Space complexity : O(N+k) to store the hash map with not more N elements and a heap with k elements.

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num: nums) {
            map.put(num, map.getOrDefault(num, 0)+1);
        }
        
        Queue<Integer> q = new PriorityQueue<> ((a,b)->map.get(a)-map.get(b));
        for (Integer key: map.keySet()) {
            q.add(key);
            if (q.size() > k) {
                q.poll();
            }
        }
        
        int[] ans = new int[k];
        int i=k;
        while (!q.isEmpty()) {
            ans[--i] = q.poll();
        }
        return ans;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值