Topic: Arrays & Hashing
Soln 1 (dictionary + lambda):
- Create an empty dictionary
- Iterate through the list "nums" with num:
- if the key [num] is not in the dictionary, then add to both the key [num] and the value [occurrence] 1 as the first occurence of that key [num]
- else it means the key [num] already exists and you need to increment the value [occurrence] in the dictionary
- Sort the dictionary items by their values in descending order, extract the keys of the top k items, and return.
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq_dict = {}
for i in nums:
if i not in freq_dict:
freq_dict[i] = 1
else:
freq_dict[i] +=1
return [item[0] for item in (sorted(freq_dict.items(), key=lambda item: item[1], reverse=True)[:k])]
Soln 2 (dictionary + lambda):
- Create an empty dictionary
- iterate through the list "nums" using num:
- get the value of num, if it exists, increment by 1, else, assign a default value of 0
- Sort the dictionary items by their values in descending order using a lambda function
- Return a list of the first k keys from the sorted dictionary.
dic = {}
for num in nums:
dic[num] = dic.get(num, 0) + 1
freq = dict(sorted(dic.items(), key=lambda x: x[1], reverse=True))
return list(freq.keys())[:k]
Notes:
A lambda is an anonymous function that can be used in place of a normal function. It can take arguments and is often used with higher-order functions.
Syntax: Lambda arguments: expression
e.g
cubed = lambda x: x**3
nums = [1, 2, 3]
cubed_nums = list(map(cubed, nums))
# Output: [1, 8, 27]
Higher-order functions, e.g map, reduce, filter, zip, sorted
Top comments (0)