Python 4 line solution. Who can tell me the time complexity


  • 0

    Get word frequency at first, make the count as negative int and sort by the (count, word) tuple.
    Pipeline {'a': 2, 'b': 3, 'c': 2} => (-2, 'a'), (-3, 'b'), (-2, 'c') => sort => (-2, 'a'), (-2, 'c'), (-1, 'b') => 'a', 'c', 'b'

    The time complexity should be python sorted?

    from collections import defaultdict
    class Solution(object):
        def topKFrequent(self, words, k):
            table = defaultdict(int)
            for w in words:
                table[w] += 1
            return [x[0] for x in sorted(table.iteritems(), key=lambda x:(-x[1], x[0]))[:k]]        
    

  • 0
    L

    It is O(n*log(n)).


Log in to reply
 

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