边工作边刷题:70天一遍leetcode: day 45-1

Top K Frequent Elements

要点:
java:

  • PriorityQueue的definition:Comparator:是一个generic interface,所以new Comparator():加括号表示,同时implement interface 用 {}。内部实现@Override int compare() function
  • 队列操作:offer/poll,map:put/get,set:add/get
  • anonymous class的function是可以直接access外部变量的,比如这题的umap
class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        from collections import Counter
        from heapq import *
        d = [(cnt, num) for num, cnt in Counter(nums).items()]
        h = []
        for i in xrange(k):
            heappush(h, d[i])
            
        for i in xrange(k, len(d)):
            if h[0][0]<d[i][0]:
                heappop(h)
                heappush(h, d[i])
        
        return [heappop(h)[1] for i in xrange(k)][::-1]

posted @ 2016-06-29 04:04  absolute100  阅读(86)  评论(0编辑  收藏  举报