smj007

Untitled

Jul 30th, 2023 (edited)
1,286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. # Same approach but two different ways of writing sam
  2. # Solution 1
  3. class Solution:
  4.     def topKFrequent(self, nums: List[int], k: int) -> List[int]:
  5.  
  6.         from collections import defaultdict
  7.  
  8.         hashmap = defaultdict(int)
  9.  
  10.         for num in nums:
  11.             hashmap[num] += 1
  12.  
  13.         keys, values = list(hashmap.keys()), list(hashmap.values())
  14.         values, keys = zip(*sorted(zip(values, keys), reverse=True))
  15.  
  16.         return keys[:k]
  17.  
  18. # Solution 2
  19. class Solution:
  20.     def topKFrequent(self, nums: List[int], k: int) -> List[int]:
  21.        
  22.         from collections import Counter
  23.         hashmap = Counter(nums)
  24.  
  25.         freqs = [[key, value] for key, value in hashmap.items()]  
  26.         freqs.sort(key = lambda x : x[1], reverse = True)
  27.        
  28.         return [x[0] for x in freqs[:k]]
  29.  
Advertisement
Add Comment
Please, Sign In to add comment