#sol
1 messages · Page 1 of 1 (latest)
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# O(n) time
if len(nums) == k:
return nums
freq = Counter(nums)
return [i for i,_ in freq.most_common(k)]
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
buckets = [[] for _ in range(len(nums) + 1)]
counter = {}
for x in nums:
if x in counter:
counter[x] += 1
else: counter[x] = 1
for x in counter:
buckets[counter[x]].append(x)
out = []
for i in range(len(buckets) - 1, -1, -1):
out.extend(buckets[i])
if len(out) == k:
return out
buckets are better cause O(N)
i'm pretty sure you can use bucket sort for O(n) worst ase
honestly, that bucket thing is too much for me
its prolly better yes, but too much of a hassle
I'm surprised they didn't put it in
I can explain my solution perfectly
even if its 4 lines
but it doesnt matter honestly as long as u get ur sol
I went with bucket sort on this one. Because Neetcode said so 😂
actually, the quickselect is N^2 in worst case
and the heap is nlogn in worst case
nah you can get O(n) quickselect
wtf is that
this looks like a college paper, I'm done with college
ya HAHA
O(n) for bucket sort seems good enough for me lololol
bucket sort is the best one for sure
trust me
but heap is next best
definitely passable
ohh bucket sort is genius!!