LeetCode:Top K Frequent Elements

来源:互联网 发布:备份同步软件 编辑:程序博客网 时间:2024/06/10 19:09

题目:Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

解题思路1:

1)使用字典,key=数组中的数,value=每个数出现的次数:

dic={} #初始化空字典for num in nums:    dic[num]=dic.get(num,0)+1

2)使用sorted排序:

sort_dic=sorted(dic.iteritems(),key=lambda d:d[1],reverse=True)"""dic.iteritems(),返回字典键值对的元祖集合key=lambda d:d[1],按照value进行排序,key=lambda d:d[0]按照key进行排序reverse=True,降序排序"""

3)新建一个list,存储返回的值

element=[]for i in range(len(sort_dic)):    element.append(sort_dic[i][0])

代码:

class Solution(object):def topKFrequent(self, nums, k):    """    :type nums: List[int]    :type k: int    :rtype: List[int]    """    dic={}    element=[]    for num in nums:        dic[num] = dic.get(num,0)+1    sort_dic=sorted(dic.iteritems(),key=lambda d:d[1],reverse=True)    for i in range(len(sort_dic)):        element.append(sort_dic[i][0])    return element[0:k]

解题思路2:

1)使用collections模块的Counter类,http://www.pythoner.com/205.html

c=collections.Counter(nums)#返回每个为nums的key-value对

2)使用heapq模块的nlargest功能,获取最大的n个元素

element=heapq.nlargest(k,c,key=lambda x:c[x])"""k:获取最大的k个元素key=lambda x:c[x]:获取key值

代码:

import collectionimport heapqclass Solution(object):def topKFrequent(self, nums, k):    """    :type nums: List[int]    :type k: int    :rtype: List[int]    """    dic=collection.Counter(nums)    return heapq.nlargest(k,dic,key=lambda x:c[x]
0 0
原创粉丝点击