窗口 — 维持一个单调递增队列
为什么要使用队列?
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
q = deque() # store index
res = []
l = r = 0
while r < len(nums):
# push
# make sure that it's a mono increasing queue
while q and nums[q[-1]] < nums[r]:
q.pop()
q.append(r)
# pop element
# since it's not in the window anymore
if l > q[0]:
q.popleft()
# append the max num in the window to res
# only when a window is formed can we move the l pointer
if (r + 1) >= k:
res.append(nums[q[0]])
l += 1
r += 1
return res
Counter得到频率表,反转频率表,再进行heapify。
heappop前k个元素,即为前K个高频元素。
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
_map = Counter(nums)
_map = [(-v, i) for i, v in _map.items()]
heapify(_map)
res = []
for i in range(k):
want = heappop(_map)
res.append(want[1])
return res
Bucket Sort
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
_map = Counter(nums)
freq = [[] for i in range(len(nums) + 1)]
for key, val in _map.items():
freq[val].append(key)
res = []
for i in range(len(freq) - 1, 0, -1):
while freq[i] and k > 0:
res.append(freq[i].pop())
k -= 1
if k == 0:
break
return res