leetcode347 Top K Frequent Elements

 1 """
 2 Given a non-empty array of integers, return the k most frequent elements.
 3 Example 1:
 4 Input: nums = [1,1,1,2,2,3], k = 2
 5 Output: [1,2]
 6 Example 2:
 7 Input: nums = [1], k = 1
 8 Output: [1]
 9 """
10 """
11 用dict实现的木桶排序
12 解法一:木桶+sort
13 解法二:木桶+heap(堆)
14 解法三:维护一个n-k的最大堆((有局限性,如果是第k大,会出问题))。此题是前k大的都append里面了
15 """
16 class Solution1:
17     def topKFrequent(self, nums, k):
18         count_list = dict()
19         res = []
20         for num in nums:
21             count_list[num] = count_list.get(num, 0) + 1
22         #如果count_list[num]没有value,则value是0,否则是value+1
23         #dict.get(key, default=None)
24         #key -- 字典中要查找的键。
25         #default -- 如果指定键的值不存在时,返回该默认值。
26         t = sorted(count_list.items(), key=lambda l: l[1], reverse=True)
27         #sorted(iterable, key=None, reverse=False)  返回的是一个list
28         #iterable -- 可迭代对象
29         #key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可         #迭代对象中的一个元素来进行排序。
30         #lambda 输入l是(key,value),输出l[1]是value. 可以理解l[0]是key
31         #reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
32         for i in range(k):
33             res.append(t[i][0]) # t[i][0]表示第i个tuple的第1个元素,t[i][1]则表示第二个元素
34         return res
35 
36 """
37 解法二:木桶+heap
38 python heap
39 nums = [2, 3, 5, 1, 54, 23, 132]
40 heap = []
41 for num in nums:
42     heapq.heappush(heap, num)  # 第一种加入堆
43 heapq.heapify(nums)  #第二种生成堆
44 print([heapq.heappop(heap) for _ in range(len(nums))])  # 堆排序结果
45 nums = [1, 3, 4, 5, 2]
46 print(heapq.nlargest(3, nums))   [5, 4, 3]
47 print(heapq.nsmallest(3, nums))  [1, 2, 3]
48 """
49 class Solution2:
50     def topKFrequent(self, nums, k):
51         import heapq
52         count_list = dict()
53         for num in nums:
54             count_list[num] = count_list.get(num, 0) + 1
55         p = list()  #存储堆排序后的结果
56         for i in count_list.items():
57             heapq.heappush(p, (i[1], i[0]))  #加入堆,每个结点是个tuple(,)
58         return [i[1] for i in heapq.nlargest(k, p)] #这里的i[1] 其实是上一行的i[0]
59 """
60 堆默认root是最小值
61 解法三:维护一个n-k的最大堆(有局限性,最大的值最后入堆,会出问题)
62 最大堆需要将最小堆的值取反
63 """
64 class Solution3:
65     def topKFrequent(self, nums, k):
66         import heapq
67         count_list = dict()
68         for num in nums:
69             count_list[num] = count_list.get(num, 0) + 1
70         p = list()
71         res = list()
72         for i in count_list.items():
73             heapq.heappush(p, (-i[1], -i[0])) #bug前面没写heapq
74             if len(p) > len(count_list) - k:
75                 _, val = heapq.heappop(p) #bug前面没写heapq
76                 res.append(-val)
77         return res

猜你喜欢

转载自www.cnblogs.com/yawenw/p/12329284.html