347. 前 K 个高频元素

题目

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:

输入: nums = [1], k = 1
输出: [1]
 

提示:

1 <= nums.length <= 105
k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
 

进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n 是数组大小。

代码

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
       Map<Integer,Integer> map=new HashMap<Integer,Integer>();
       int[] array=new int[k];
       for(int num:nums)
       {
           map.put(num,map.getOrDefault(num,0)+1);
       }   
      // System.out.println(map); 
       PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer a, Integer b) {
                return map.get(b) - map.get(a);
            }
        });
        for(Integer key : map.keySet())
       {
           //if(pq.size())
           //System.out.println(" key"+key+"value"+map.get(key)); 
           pq.offer(key);
           //System.out.println(pq); 
       }        
       for(int i=0;i<k;i++)
       array[i]=pq.poll();
       return array;
      /*
       for (Integer key : map.keySet()) {
            if (pq.size() < k) {
                pq.add(key);
                System.out.println(pq);
            } else if (map.get(key) > map.get(pq.peek())) {
                pq.remove();
                pq.add(key);
            }
        }
        System.out.println(pq);
        // 取出最小堆中的元素
        List<Integer> res = new ArrayList<>();
        while (!pq.isEmpty()) {
            res.add(pq.remove());
        }
        return res.stream().mapToInt(Integer::valueOf).toArray();

*/


    
}
}

反思

1、优先队列的相关知识

add()和offer()

add(E e)offer(E e)的语义相同,都是向优先队列中插入元素,并对堆进行调整

element()和peek()

element()peek()的语义完全相同,都是获取但不删除队首元素

remove()和poll()

remove()poll()方法的语义也完全相同,都是获取并删除队首元素,为维护小顶堆的性质,需要进行必要的调整。

remove(Object o) 

remove(Object o)方法用于删除队列中跟o相等的某一个元素(如果有多个相等,只删除一个)

//自定义比较器,降序排列
static Comparator<Integer> cmp = new Comparator<Integer>() {
      public int compare(Integer e1, Integer e2) {
        return e2 - e1;
      }
    };

2、好的思路。加入的是 数组,排序是按递增排序。

class Solution {
public:
    static bool cmp(pair<int, int>& m, pair<int, int>& n) {
        return m.second > n.second;
    }

    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> occurrences;
        for (auto& v : nums) {
            occurrences[v]++;
        }

        // pair 的第一个元素代表数组的值,第二个元素代表了该值出现的次数
        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> q(cmp);
        for (auto& [num, count] : occurrences) {
            if (q.size() == k) {
                if (q.top().second < count) {
                    q.pop();
                    q.emplace(num, count);
                }
            } else {
                q.emplace(num, count);
            }
        }
        vector<int> ret;
        while (!q.empty()) {
            ret.emplace_back(q.top().first);
            q.pop();
        }
        return ret;
    }
};

桶排序

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> frequencyForNum = new HashMap<>();
    for (int num : nums) {
        frequencyForNum.put(num, frequencyForNum.getOrDefault(num, 0) + 1);
    }//key 数,value,频率
    List<Integer>[] buckets=new ArrayList[nums.length+1];
    //List<Integer>[] buckets = new ArrayList[nums.length + 1];
    for(int key:frequencyForNum.keySet())
    {
        if(buckets[frequencyForNum.get(key)]==null)
        buckets[frequencyForNum.get(key)]=new ArrayList<>();
        buckets[frequencyForNum.get(key)].add(key);
    }
    List<Integer> topK = new ArrayList<>();
    for(int i=buckets.length-1;i>=0&&topK.size()<k;i--)
    {
        if(buckets[i]==null)
        continue;
        if(buckets[i].size()<=(k-topK.size()))
        topK.addAll(buckets[i]);
        else topK.addAll(buckets[i].subList(0,k-topK.size()));
    }
    int[] num=new int[k];
    for(int i=0;i<k;i++)
    {
        num[i]=topK.get(i);
    }
    return num;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值