1. 程式人生 > >347. Top K Frequent Elements(python+cpp)

347. Top K Frequent Elements(python+cpp)

題目:

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; } };

總結: