[LeetCode] 347. 前K个高频元素

python 版方法1:链表

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        sets=list(set(nums))
        count=[[sets[i],nums.count(sets[i])] for i in range(len(sets))]#第一维元素,第二维对应出现次数
        count1=sorted(count,key=lambda x: x[1],reverse=True) #按第二维进行降序排序
        topK=[count1[i][0] for i in range(k)]
        return topK

采用sorted()函数对多维数组按照其中某一维进行排序参见:http://www.runoob.com/python/python-func-sorted.html 

 

python 版方法2:top K之最小堆实现

https://mp.weixin.qq.com/s?__biz=MzI3NTkyMjA4NA==&mid=2247484955&idx=1&sn=fe487b4baba4109a6e76ec5410f8ecd4&chksm=eb7c2bd0dc0ba2c67b87e717cd6f93cff506140fa787f2a0d53372f7964f192aa523848cf69f&scene=21#wechat_redirect

 

python 版方法3:top K之快排实现

https://mp.weixin.qq.com/s?__biz=MzI3NTkyMjA4NA==&mid=2247485012&idx=1&sn=eed804a55198d5eb647f4e7acd3e9bfe&chksm=eb7c2b9fdc0ba2899935a32a4e213544847e8cb18bbbd8db4788cc5deb0454e0f83f6799d130&scene=21#wechat_redirect

 

扩展,对于python中两个list(长度相同),当一个list排序之后,另一个list如何按照对应索引进行变换?

a=[3,2,4,1]
b=[103,109,108,100]
c=list(zip(a,b)) #两个一维链表合并维一个二维链表
sort_c=sorted(c, key=lambda x: x[1],reverse=True) #按照第二维排序
print(sort_c)

输出:

 

posted @ 2019-03-15 21:58  Nice_to_see_you  阅读(228)  评论(0编辑  收藏  举报