title: ‘’‘LEETCODE-DAY13’‘’
date: 2024-03-04 14:00:09
tags:
今日题目:(栈与队列)239. 滑动窗口最大值、347.前 K 个高频元素
T1
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
res=list()
n=len(nums)
for i in range(n-k+1):
c=max(nums[i:i+k])
res.append(c)
return res
超出时间限制 37 / 51 个通过的测试用例
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
res=list()
n=len(nums)
l=nums[0:k]
for i in range(n-k+1):
if i >0:
l.append(nums[i+k-1])
l.pop(0)
c=max(l)
res.append(c)
else:
c=max(l)
res.append(c)
return res
超出时间限制 37 / 51 个通过的测试用例
超时原因分析:每个元素经过了k次比较,时间复杂度是O(n*k)
改进算法目标是减少重复比较的次数
考虑构造单调队列,使得队列头部始终为窗口中最大的元素
T2
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
table=dict()
for i in nums:
if i not in table.keys():
table[i]=1
else:
table[i]+=1
res=table.keys()
return res[0:k]
TypeError: ‘dict_keys’ object is not subscriptable
~~~^^^^^
return res[0:k]
Python语法:1.dict.keys()常见错误
原因:dict_keys([‘no surfacing’,‘flippers’]),返回的是一个 dict_keys 对象,不再是 list 类型,也不支持 index 索引
所以强制转成 list 类型即可使用
enumerate可利用列表元组等序列,生成类似字典的结构。实践中别用反
4.table[i] = table.get(i,0) + 1,table字典中获取键为i的-值,如果i不存在于字典中,则返回默认值0。然后将获取到的值加1。
del my_dict[‘a’],del关键字被用来删除字典my_dict中的键为’a’的键值对。
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
n=len(nums)
table=dict()
res=list()
for i in nums:
if i not in table.keys():
table[i]=1
else:
table[i]+=1
#查value中最大k个值对应的key
new_table=dict()
for key,value in enumerate(table):
new_table[value]=key
w=list(table.values())
w.sort(reverse=True)
for i in w[0:k]:
x=new_table[i]
res.append(x)
return res
输入
nums =
[1]
k =
1
输出
[0]
预期结果
[1]
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
n=len(nums)
table=dict()
res=list()
for i in nums:
if i not in table.keys():
table[i]=1
else:
table[i]+=1
new_table=dict()
for key,value in table.items():
new_table[value]=key
w=list(table.values())
w.sort(reverse=True)
for i in table:
if table[i] in w[0:k]:
res.append(i)
return res
nums =
[1,2]
k =
2
输出
[2,2]
预期结果
[1,2]
出错原因在于此时table={1:1,2:1},table.values=[1,1]
翻转后new_table 的key=1 无法同时对应到1和2
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
n=len(nums)
table=dict()
res=list()
for i in nums:
if i not in table.keys():
table[i]=1
else:
table[i]+=1
w=list(table.values())
w.sort(reverse=True)
for i in table:
if table[i] in w[0:k]:
res.append(i)
return res
此为暴力解法,时间复杂度O(NlogN)
第一个for循环也可等价写成
for i in nums:
table[i]=table.get(i,0)+1