347. Top K Frequent Elements(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84305637

题目:

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.

解释:
第一反应就是先Counter(),再根据value排序再取前k个,但是感觉这样速度太慢了。
Counter()有自己的most_common(k)函数,甚至不用自己排序了,但是速度居然更慢了。
python代码:

from collections import Counter
class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        count_dict=Counter(nums)
        return [ x for (x,y) in sorted(count_dict.items(),key = lambda x:x[1],reverse = True)[:k]]

c++代码:

#include <map>
using namespace std;
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        map<int ,int> _count;
        for (auto num:nums)
            _count[num]+=1;
        vector<pair<int,int>>count_pair(_count.begin(),_count.end());
        sort(count_pair.begin(),count_pair.end(),comp);
        vector<int>result;
        for (int i=0;i<k;i++)
            result.push_back(count_pair[i].first);
        return result;
    }
    static bool comp(const pair<int,int>& item1,const pair<int,int>& item2)
    {
        return item1.second>item2.second;
    }
};

总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/84305637