LEETCODE-DAY13

文章讨论了如何优化两个LeetCode题目,一个是使用单调队列减少滑动窗口最大值问题中的比较次数,另一个是使用Python字典和排序找出前K个高频元素。作者分析了原始算法的时间复杂度并提供了改进版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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 类型即可使用

2.python字典由value查key的三种方法

3.enumerate与dict.items()

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值