Skip to content

Instantly share code, notes, and snippets.

@jeffchiucp jeffchiucp/top2Frequent.py Secret
Last active Jul 23, 2018

Embed
What would you like to do?
top2Frequent.py
#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]
@jeffchiucp

This comment has been minimized.

Copy link
Owner Author

commented Jul 23, 2018

Without using the built-in collections module, the above code will work:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.