这题是统计前K个最长使用的字母。在统计数量里面,python有一个collections库,里面的一个Counter函数就是用来干这个的。所以做起来很方便。
from collections import Counter
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
c = Counter(nums)
c = c.most_common(k)
for i in xrange(len(c)):
c[i] = c[i][0]
return c