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.
defintersect(self, nums1: List[int], nums2: List[int]) -> List[int]: num_to_count = collections.Counter(nums1) res = [] for n in nums2: if n in num_to_count and num_to_count[n] > 0: num_to_count[n] -= 1 res.append(n) return res
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
defremoveDuplicateLetters(self, s: str) -> str: char_to_count = collections.Counter(s) stack, stack_set = [], set() for i in range(len(s)): char_to_count[s[i]] -= 1 if s[i] in stack_set: continue while stack and s[i] < stack[-1] and char_to_count[stack[-1]] > 0: stack_set.remove(stack[-1]) stack.pop() stack.append(s[i]) stack_set.add(s[i]) return''.join(stack)
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.
Find the maximum coins you can collect by bursting the balloons wisely.
Note: (1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them. (2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
defmaxCoins(self, nums: List[int]) -> int: ary = list(nums) ary.insert(0, 1) ary.append(1) N = len(ary) dp = [[0for _ in range(N)] for _ in range(N)] for k in range(2, N): for i in range(0, N - k): j = i + k for m in range(i + 1, j): dp[i][j] = max(dp[i][j], dp[i][m] + ary[i] * ary[m] * ary[j] + dp[m][j]) return dp[0][N - 1]