deftopKFrequent(self, nums: List[int], k: int) -> List[int]: dict = {} for i in range(len(nums)): if nums[i] notin dict: dict[nums[i]] = 1 else: dict[nums[i]] += 1
freq_dict = [(v, k) for k, v in dict.items()] res = [] for i in range(len(freq_dict)): if i < k: heappush(res, freq_dict[i]) elif freq_dict[i][0] > res[0][0]: heapreplace(res, freq_dict[i])
from heapq import heapreplace, heappush from collections import Counter
deftopKFrequent(self, nums: List[int], k: int) -> List[int]: dict = Counter(nums) freq_dict = [(v, k) for k, v in dict.items()] res = [] for i in range(len(freq_dict)): if i < k: heappush(res, freq_dict[i]) elif freq_dict[i][0] > res[0][0]: heapreplace(res, freq_dict[i])
public List<Integer> topKFrequent(int[] nums, int k){ List<Integer> result = new ArrayList<Integer>(); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0;i<nums.length;i++){ if(map.containsKey(nums[i])) map.put(nums[i], map.get(nums[i])+1); else map.put(nums[i], 1); } Node[] f = new Node[map.size()]; Iterator it = map.entrySet().iterator(); int j=0; while(it.hasNext()){ Map.Entry pair = (Map.Entry)it.next(); Node node = new Node((int)pair.getKey(), (int)pair.getValue()); f[j++] = node; } hselect(f, k); for(int i=0;i<k;i++) result.add(f[i].key); return result; } publicvoidhselect(Node a[], int k){ // min heap with size=k for (int i = k / 2; i >= 0; i--) { minHeapify(a, i, k); } for (int i = k; i < a.length; i++) { if (a[i].value > a[0].value) { swap(a, i, 0); minHeapify(a, 0, k); } } }
publicvoidminHeapify(Node[] arr, int i, int n){ int smallest = i; int l = left(i); int r = l + 1; if (l < n && arr[l].key < arr[smallest].key) smallest = l; if (r < n && arr[r].key < arr[smallest].key) smallest = r; if (smallest != i) { swap(arr, i, smallest); minHeapify(arr, smallest, n); } }
privateintleft(int i){ return2 * i + 1; }
privatevoidswap(Node[] arr, int index1, int index2){ Node tmp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = tmp; }
classNode{ int key; int value; publicNode(int k, int v){ key = k; value = v; } public String toString(){ return"("+key+","+value+")"; } }
桶排序要用List串联起元素,例如[1,2],k=2,频数为1的元素有两个,所以桶的内容应该是List。Python用[[] for _ in range(len(nums) + 1)]
桶数量为原数组大小+1,例如一个元素[1], 它的频数为1,而频数为0是不会出现。
逆序遍历所有桶,只要结果集个数为k,就停止循环。
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
from collections import Counter
deftopKFrequent(self, nums: List[int], k: int) -> List[int]: di = Counter(nums) freq = [[] for _ in range(len(nums) + 1)] for key, val in di.items(): freq[val].append(key) res = [] for i in range(len(freq) - 1, 0, -1): for n in freq[i]: if k > 0: res.append(n) k -= 1 return res
题目可以包装成:给定一个文档,返回其前k个出现次数最多的单词。 Given a document, return the k most frequent words. Assume punctuation are removed. Given a non-empty array of strings, return the k most frequent elements.