public class Solution { public IList<int> TopKFrequent(int[] nums, int k) { var dic = new Dictionary<int, int>(); foreach (var num in nums) { if (!dic.ContainsKey(num)) { dic.Add(num, 1); } else { dic[num]++; } } var list = dic.OrderByDescending(x => x.Value).ToList(); var listR = new List<int>(); for (int i = 0; i < k; i++) { listR.Add(list[i].Key); } return listR; } }
https://leetcode.com/problems/top-k-frequent-elements/#/description
补充一个python的实现,使用封装好的类库,代码很简洁。
1 import collections 2 import heapq 3 4 class Solution: 5 def topKFrequent(self, nums, k): 6 count = collections.Counter(nums) 7 return heapq.nlargest(k, count.keys(), key=count.get)