An easy python solution!


  • 1
    L
    from heapq import *
    class Solution(object):
        def topKFrequent(self, words, k):
            """
            :type words: List[str]
            :type k: int
            :rtype: List[str]
            """
            dic = {}
            for i in words:
                dic[i] = dic.get(i, 0) - 1
            tu = [(i, n) for n, i in dic.items()]
            h = nsmallest(k, tu)
            return [i[1] for i in h]
    

  • 0
    A

    nsmallets() on tu is O(nlg(n)), not O(nlg(k)), since the heap size is n.


  • 0
    N

    @algowl Heap size is k not n here since the argument to nsmallest is k.


Log in to reply
 

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