Python using standard libraries


  • 0
    Y
    def top_k_frequent(xs, k):
        hist = collections.Counter(xs)
        heap = []
        for x, freq in hist.iteritems():
            heapq.heappush(heap, (freq, x))
            if len(heap) > k:
                heapq.heappop(heap)
        return [t[1] for t in heapq.nlargest(k, heap)]
    

Log in to reply
 

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