Skip to content

Instantly share code, notes, and snippets.

@jeffchiucp
Last active July 23, 2018 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffchiucp/2e733e57476bd697bc430cdf48f6e180 to your computer and use it in GitHub Desktop.
Save jeffchiucp/2e733e57476bd697bc430cdf48f6e180 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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