347. Top K Frequent Elements pair的使用

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.
  • It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique.
  • You can return the answer in any order.

题目链接:https://leetcode.com/problems/top-k-frequent-elements/

思路:先用map统计每个元素出现的次数,因为sort无法直接对map排序,再把元素放到一个vector<pair<int, int>> 中

这题map不需要有序,用unordered_map一点。

class Solution {
public:
    static bool cmp(pair<int,int> a,pair<int,int>b)
    {
        return a.second<b.second;
    }
    vector<int> topKFrequent(vector<int>& nums, int k) {
        map<int,int> mp;
        vector<int> res;
        for(auto it:nums)
        {
            mp[it]++;
        }
        vector<pair<int,int>> vc;
        for(auto it:mp)
        {
            vc.emplace_back(make_pair(it.first,it.second));
        }
        sort(vc.begin(),vc.end(),cmp);
        for(int i=0;i<k;i++)
        {
            res.emplace_back(vc[vc.size()-1-i].first);
        }
        return res;
    }
};
class Solution {
    /**
    2024年8月22日22:32:33
    遍历数组,同时使用map记录每个元素出现的次数,
    然后再遍历map,把元素按照次数放到最小堆里,
    这个堆里就只会存储前k大的元素了,
    最小堆的比较方式要熟悉下怎么自定义写
     */
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map=new HashMap<>();
        for(int num:nums){
            // 学会使用getOrDefault方法,更简洁
            map.put(num,map.getOrDefault(num,0)+1);
            // if(map.get(num)==null){
            //     map.put(num,1);
            // } else {
            //     map.put(num,map.get(num)+1);
            // }
        }
        PriorityQueue<Integer> minHeap=new PriorityQueue<>((a,b)->(map.get(a)-map.get(b)));
        for(Integer key:map.keySet()){
            minHeap.offer(key);
            if(minHeap.size()>k){
                minHeap.poll();
            }
        }
        int[] res=new int[k];
        int c=0;
        while(!minHeap.isEmpty()){
            res[c++]=minHeap.poll();
        }
        return res;
     }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值