-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
most-frequent-ids.py
58 lines (51 loc) · 1.46 KB
/
most-frequent-ids.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
# Time: O(nlogn)
# Space: O(n)
import collections
import itertools
import heapq
# heap
class Solution(object):
def mostFrequentIDs(self, nums, freq):
"""
:type nums: List[int]
:type freq: List[int]
:rtype: List[int]
"""
result = []
cnt = collections.Counter()
max_heap = []
for x, f in itertools.izip(nums, freq):
cnt[x] += f
heapq.heappush(max_heap, (-cnt[x], x))
while max_heap and -max_heap[0][0] != cnt[max_heap[0][1]]:
heapq.heappop(max_heap)
result.append(-max_heap[0][0] if max_heap else 0)
return result
# Time: O(nlogn)
# Space: O(n)
import collections
import itertools
from sortedcontainers import SortedList
# sorted list
class Solution2(object):
def mostFrequentIDs(self, nums, freq):
"""
:type nums: List[int]
:type freq: List[int]
:rtype: List[int]
"""
result = []
cnt = collections.Counter()
cnt2 = collections.Counter()
sl = SortedList()
for x, f in itertools.izip(nums, freq):
sl.discard((cnt[x], cnt2[cnt[x]]))
cnt2[cnt[x]] -= 1
if cnt2[cnt[x]]:
sl.add((cnt[x], cnt2[cnt[x]]))
cnt[x] += f
sl.discard((cnt[x], cnt2[cnt[x]]))
cnt2[cnt[x]] += 1
sl.add((cnt[x], cnt2[cnt[x]]))
result.append(sl[-1][0])
return result