classSolution { public: vector<int> topKFrequent(vector<int>& nums, int k){ unordered_map<int, int> freq; for (auto num : nums) freq[num]++;
vector<vector<int>> buckets(nums.size()+1); for (auto [a, b] : freq) buckets[b].push_back(a);
vector<int> res;
// use the bucket to sort by freq with O(N) time for (int i = nums.size(); k > 0; i--) { // freq from high to low for (auto a : buckets[i]) { res.push_back(a); k--; } }
classCodec: defencode(self, strs: List[str]) -> str: """Encodes a list of strings to a single string. """ res = "" for s in strs: res += str(len(s)) + "#" + s return res
defdecode(self, s: str) -> List[str]: """Decodes a single string to a list of strings. """ res, i = [], 0
while i < len(s): j = i while s[j] != "#": j += 1 length = int(s[i: j]) res.append(s[j + 1: j + 1 + length]) i = j + 1 + length
return res
# Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(strs))
# eg. "5#hello5#World"
Time: O(N) Space: O(1)
128. Longest Consecutive Sequence
1 2 3
Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
sorting
Time: O(NlogN)
two pointers
1 2 3 4 5 6 7 8 9 10 11
classSolution: deflongestConsecutive(self, nums: List[int]) -> int: nums = set(nums) maxLen = 0 for x in nums: if x - 1notin nums: y = x + 1 while y in nums: y += 1 maxLen = max(maxLen, y - x) return maxLen