I'm using python language. The clear algorithm will be enough for me.
I've tried using a dictionary, and counting the existence of each character if it is not in the list. But I'm not sure if it has the possible less complexity.
I'm using python language. The clear algorithm will be enough for me.
I've tried using a dictionary, and counting the existence of each character if it is not in the list. But I'm not sure if it has the possible less complexity.
Use the in built Counter(list).most_common(n) method, as below.
from collections import Counter
input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 5, 7, 3, 1]
most_common_values = [value[0] for value in Counter(input_list).most_common(2)]
print(most_common_values)
This outputs: [1, 2]
.
The advantages to this approach are that it is fast, simple, and returns a list of the items in order. In addition, if their is a 'tie' in value count, it will return the example that appears first, as displayed in the example above.