-
-
Save jeffchiucp/2e733e57476bd697bc430cdf48f6e180 to your computer and use it in GitHub Desktop.
top2Frequent.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import collections | |
def top2Frequent(nums): | |
""" | |
:type nums: List[int] | |
:type k: int | |
:rtype: List[int] | |
""" | |
if len(nums) < 2: | |
return [] | |
counter = {} | |
for num in nums: | |
if num in counter: | |
counter[num] = counter[num] + 1 | |
else: | |
counter[num] = 1 | |
# The line below creates an iterator that will generate the | |
# sequence [(4, 3), (3, 2), (5, 1), (1, 1)], i.e. | |
# count the occurrence for each value. | |
# In particular, sorted() with key=lambda kv: kv[1] will turn | |
# a dictionary into a list of tuples, sorted by the second item | |
# of each tuple | |
sorted_by_value = reversed(sorted(counter.items(), key=lambda kv: kv[1])) | |
top_vals = [item[0] for item in sorted_by_value][:2] | |
return top_vals | |
""" | |
bucket = collections.defaultdict(list) | |
for key in freq: | |
f = freq[key] | |
bucket[f].append(key) | |
res = [] | |
count = len(nums) # the upper limit for res | |
while len(res) < 2: | |
if bucket[count]: | |
res += bucket[count] | |
count -= 1 | |
return res | |
""" | |
nums = [1, 4, 3, 4, 5, 3, 4] # [4,3] | |
solution = top2Frequent(nums) | |
print(solution) # [4,3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Without using the built-in collections module, the above code will work: