[LeetCode] 347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

题意:给一组数,找出前k频率的数

解法一,利用排序,我们构造一个数据结构记录每个数的值和频率(类似的思想可以开一个堆,用堆操作)

class Solution {
    private class node implements Comparable<node>{
        public int num;
        public int freq;
        public node(int num, int freq) {
            this.num = num;
            this.freq = freq;
        }
        @Override
        public int compareTo(node o) {
            if (this.freq < o.freq)
                return 1;
            if (this.freq > o.freq)
                return -1;
            return 0;
        }
    }
    public List<Integer> topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int n: nums){
            map.put(n, map.getOrDefault(n,0)+1);
        }
        List<Integer> res = new ArrayList<>(k);
        node[] nodes = new node[map.size()];
        int i = 0;
        for (Map.Entry entry: map.entrySet()) {
            int num = (int) entry.getKey();
            int freq = (int) entry.getValue();
            node nd = new node(num, freq);
            nodes[i] = nd;
            i++;
        }
        Arrays.sort(nodes);
        for (i = 0; i < k; i++) {
            res.add(nodes[i].num);
        }
        return res;
    }
}

解法二:利用TreeMap,TreeMap是基于红黑树的,自排序,注意一点就是你要排序的对象就行了

public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int n: nums){
            map.put(n, map.getOrDefault(n,0)+1);
        }

        TreeMap<Integer, List<Integer>> fremap = new TreeMap<>();
        for (int num : map.keySet()) {
            if (!fremap.containsKey(map.get(num))) {
                fremap.put(map.get(num), new LinkedList<>());
            }
            fremap.get(map.get(num)).add(num);
        }

        List<Integer> res = new ArrayList<>();
        

        while (res.size() < k) {
            Map.Entry<Integer, List<Integer>> entry = fremap.pollLastEntry();

            res.addAll(entry.getValue());
            
        }
        return res;
    }
}

 

转载于:https://www.cnblogs.com/Moriarty-cx/p/9788445.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值