Python Solution 76 ms (using a Counter)


  • 0
    G
    from collections import Counter
    myItems = Counter(nums)
    return sorted(myItems, key=myItems.get, reverse=True)[:k]
    

    A Counter simply counts the number of occurrences of an element in an iterable and returns a dictionary mapping element to number of occurrences. Then, we can sort by the number of occurrences in descending order and take the top k. Should take linear time (in the size of nums) to create the dictionary and then m log m time to sort the elements (where m is the number of unique items).


  • 0
    G

    I got 44ms using the counter but I didn't use the sorted function

    return [x[0] for x in Counter(nums).most_common(k)]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.