239.滑动窗口最大值
- 主要思路-单调队列
- V1 :自己用list写了一个单调队列的思路,但是list的pop(-1)时间复杂度为O(n),刚好卡到限制时间过
- V2:用内置的deque的双端队列实现双端输入输出
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
mon_queue = []
ans = []
idx = 0
for i in range(k):
if mon_queue and mon_queue[0]<nums[i]:
mon_queue = [nums[i]]
# elif not mon_queue or mon_queue[-1]>=nums[i]:
# mon_queue.append(nums[i])
else:
while(mon_queue and mon_queue[-1]<nums[i]):
mon_queue.pop(-1)
mon_queue.append(nums[i])
if mon_queue:
ans.append(mon_queue[0])
for i in range(k,len(nums)):
if nums[i-k]==mon_queue[0]:
mon_queue.pop(0)
while(mon_queue and mon_queue[-1]<nums[i]):
mon_queue.pop(-1)
mon_queue.append(nums[i])
ans.append(mon_queue[0])
return ans
## V2
from collections import deque
class Myqueue():
def __init__(self):
self.queue = deque()
def pop(self,num):
if self.queue and num == self.deque[0]:
self.queue.popleft()
def push(self,num):
while self.queue and num>self.queue[-1]:
self.queue.pop()
self.queue.append(num)
def getfront(self):
return self.queue[0]
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
mon_queue = Myqueue()
ans = []
for i in range(k):
mon_queue.push(nums[i])
if mon_queue:
ans.append(mon_queue.getfront())
for i in range(k,len(nums)):
mon_queue.pop(nums[i-k])
mon_queue.push(nums[i])
ans.append(mon_queue.getfront())
return ans
347.前 K 个高频元素
-题目要求时间复杂度优于为O(nlogn)
- Step1:哈希表记录出现的次数
- Step2:V1:全排序,时间复杂度为O(nlogn),不符合题目要求; V2: 只维护前k个元素,只排序k个
## V1
import collections
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
dicts = collections.defaultdict(int)
for i in nums:
dicts[i] += 1
dicts = sorted(dicts.items(),key=lambda d:d[1],reverse = True)
ans = []
for i in range(k):
ans.append(dicts[i][0])
return ans[:k]
import collections,heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
dicts = collections.defaultdict(int)
for i in nums:
dicts[i] += 1
que = []
for key,freq in dicts.items():
heapq.heappush(que,(freq,key))
if len(que)>k:
heapq.heappop(que)
ans = []
for i in range(k):
ans.append(heapq.heappop(que)[1])
return ans