讨论/《中级算法》 - 前 K 个高频元素/
《中级算法》 - 前 K 个高频元素
共 3 个回复

Dictionary计数之后用Linq排序,本来觉得挺睿智的,没想到结果这么奇妙。

using System.Linq;
public class Solution {
    public int[] TopKFrequent(int[] nums, int k)
        {
            Dictionary<int, int> dic = new Dictionary<int, int>();
            foreach(int x in nums)
            {
                if (dic.ContainsKey(x))
                {
                    dic[x]++;
                }
                else
                {
                    dic.Add(x, 1);
                }
            }           
            var myList = dic.ToList();
            myList.Sort((pair1, pair2) =>- pair1.Value.CompareTo(pair2.Value));
            int[] result = new int[k];
            for(int i = 0; i < result.Length; i++)
            {
                result[i] = myList[i].Key;
            }
            return result;
        }
}

Snipaste_2021-04-26_20-16-38.png

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        return [i[0] for i in Counter(nums).most_common(k)]

我豁出去了

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> result;
        unordered_map<int,int> freq;
        priority_queue<pair<int, int>> pq;

        for (int i = 0; i < nums.size(); i++) {
            ++freq[nums[i]];
        }

        for (auto numpair : freq) {
            pq.push(pair<int,int>{numpair.second, numpair.first});
            //if (pq.size() > k) pq.pop();
        } 
        for (int i = 0; i < k; ++i) {
            result.push_back(pq.top().second);
            pq.pop();
        }
        return result;
    }
};