Majority element
Today's AlgoDaily task was to find an element (if it exists) that has a frequency of more than 0.5 in a list. This element is called the majority element.
For example, in the list [4,2,4] 4 is the majority element, because it occurs more often than 0.5. In the list [4,2,4,2] there is no majority element.
I wrote an implementation with linear complexity using a hash table (dictionary in python). You first scan through the list and populate the hash table with counts of elements that you see. Then you sum the values of the hash table (this is linear) and then you do another linear scan through the keys of the hash table and try to find the element whose count/len(original list) is greater than 0.5. If such an element exists return it, otherwise there is no majority element.
The solution is here: https://github.com/mariakesa/Algorithms/blob/master/AlgoDaily/AlgorithmsPractice.ipynb
Kommentaarid
Postita kommentaar