LeetCode | 239. Sliding Window Maximum, 347. Top K Frequent Elements

文章介绍了如何使用单调队列解决LeetCode的239题——滑动窗口最大值,以及利用优先队列解决347题——TopK频繁元素。在滑动窗口最大值问题中,通过维护一个降序的单调队列,可以有效地找到每个窗口的最大值。而在查找TopK频繁元素时,利用优先队列(升序)配合频率映射,能有效找出出现频率最高的k个元素。
摘要由CSDN通过智能技术生成

239. Sliding Window Maximum

Link: https://leetcode.com/problems/sliding-window-maximum/

Description

You are given an array of integers 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.
Return the max sliding window.

Approach

Monotonic Queue

We want to design a queue that the numbers in the queue are sorted in descending order. As we only care about the max number of size k. This array only needs to maintain at most k numbers.
在这里插入图片描述

  • Initialize a ArrayDeque queue, a int array result.
  • For n in nums:
    • If the queue is not empty and contains k numbers, the top of the queue equals to n, remove the top of the queue.
    • While the last item of queue less than n, remove the last item iteratively until the queue is empty or the last item greater than or equal to n.
    • Add n to the queue.
    • If n >= k - 1, add the top of the queue to result.

Solution

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        ArrayDeque<Integer> queue = new ArrayDeque<>();
        int[] result = new int[nums.length - k + 1];
        for (int i = 0; i < nums.length; i++) {
            if (!queue.isEmpty() && i - k >= 0 && queue.peek() == nums[i - k])
                queue.remove();
            while (!queue.isEmpty() && queue.peekLast() < nums[i])
                queue.removeLast();
            queue.add(nums[i]);
            if (i >= k - 1)
                result[i - k + 1] = queue.peek();
        }
        return result;
    }
}

347. Top K Frequent Elements

Link: https://leetcode.com/problems/top-k-frequent-elements/

Description

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Approach

Priority Queue

  • Initialize a map to collect the numbers and their frequencies.
  • Initialize a priority queue of ascending order.
  • Add the entries of map to the queue, if the size of the queue larger than k, pop the top of the queue.

Solution

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] result = new int[k];
        for (int n: nums)
            map.put(n, map.getOrDefault(n, 0) + 1);
        PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> (o1[1] - o2[1]));
        for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
            pq.add(new int[]{entry.getKey(), entry.getValue()});
            if (pq.size() > k)
                pq.remove();
        }
        for (int i = 0; i < k; i++) 
            result[i] = pq.remove()[0];
        return result;
    }
}

Reference: https://programmercarl.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值