leetcode 347. Top K Frequent Elements 使用HashMap计数

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

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.

这道题很简单,直接使用HashMap计数,然后排序即可。

代码如下:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


class Solution 
{
    public List topKFrequent(int[] nums, int k) 
    {
        List res=new ArrayList();
        if(nums==null || nums.length<=0 || k<=0 || k>=nums.length+1)
            return res;

        Map map=new HashMap();
        for(int i=0;i0)+1);

        List> list = new ArrayList>(map.entrySet());
        Collections.sort(list, new Comparator>() {
            @Override
            public int compare(Entry a,Entry b) {               
                return b.getValue()-a.getValue();  
            } });

        for(int i=0;ireturn res;
    }
}

下面是C++的做法,直接统计计数即可

代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;


bool cmp(pair<int, int> a, pair<int, int> b)
{
    return a.second >= b.second;
}

class Solution
{
public:
    vector<int> topKFrequent(vector<int>& nums, int k)
    {
        map<int, int> mmp;
        for (int i : nums)
            mmp[i]++;
        vectorint, int>> all;
        for (auto i : mmp)
            all.push_back({ i.first,i.second });
        sort(all.begin(), all.end(), cmp);

        vector<int> res;
        for (int i = 0; i < k; i++)
            res.push_back(all[i].first);
        return res;
    }
};

你可能感兴趣的:(leetcode,For,Java,leetcode,For,C++)