-
Notifications
You must be signed in to change notification settings - Fork 43
/
top-k-frequent-elements.py
146 lines (120 loc) · 4.14 KB
/
top-k-frequent-elements.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
"""
347. Top K Frequent Elements
Medium
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.length <= 105
k is in the range [1, the number of unique elements in the array].
It is guaranteed that the answer is unique.
Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
"""
# V0
import collections
class Solution(object):
def topKFrequent(self, nums, k):
freq_dict = dict(collections.Counter(nums))
# python sort a dict by value
# https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value
return [ x[0] for x in sorted(list(freq_dict.items()), key=lambda x: x[1],reverse=True) ][:k]
# V1
import collections
class Solution(object):
def topKFrequent(self, nums, k):
freq_dict = dict(collections.Counter(nums))
# python sort a dict by value
# https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value
return [ x[0] for x in sorted(list(freq_dict.items()), key=lambda x: x[1],reverse=True) ][:k]
# V1'
# https://www.jiuzhang.com/solution/top-k-frequent-elements/#tag-highlight-lang-python
class Solution:
def topKFrequent(self, nums, k):
# 统计元素的频率
freq_dict = dict()
for num in nums:
freq_dict[num] = freq_dict.get(num, 0) + 1
freq_dict_sorted = sorted(freq_dict.items(), key=lambda x: x[1], reverse=True)
ret = list()
for i in range(k):
ret.append(freq_dict_sorted[i][0])
return ret
# V2
# Time: O(n)
# Space: O(n)
import collections
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
counts = collections.Counter(nums)
buckets = [[] for _ in range(len(nums)+1)]
for i, count in counts.items():
buckets[count].append(i)
result = []
for i in reversed(range(len(buckets))):
for j in range(len(buckets[i])):
result.append(buckets[i][j])
if len(result) == k:
return result
return result
# V3
# Time: O(n) ~ O(n^2), O(n) on average.
# Space: O(n)
# Quick Select Solution
from random import randint
class Solution2(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
counts = collections.Counter(nums)
p = []
for key, val in counts.items():
p.append((-val, key))
self.kthElement(p, k)
result = []
for i in range(k):
result.append(p[i][1])
return result
def kthElement(self, nums, k):
def PartitionAroundPivot(left, right, pivot_idx, nums):
pivot_value = nums[pivot_idx]
new_pivot_idx = left
nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
for i in range(left, right):
if nums[i] < pivot_value:
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx
left, right = 0, len(nums) - 1
while left <= right:
pivot_idx = randint(left, right)
new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums)
if new_pivot_idx == k - 1:
return
elif new_pivot_idx > k - 1:
right = new_pivot_idx - 1
else: # new_pivot_idx < k - 1.
left = new_pivot_idx + 1
# V4
# Time: O(nlogk)
# Space: O(n)
class Solution3(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
return [key for key, _ in collections.Counter(nums).most_common(k)]