当前位置: 首页 > news >正文

力扣提升第一天

力扣提升第一天

题目链接:https://leetcode.cn/problems/design-memory-allocator/?envType=daily-question&envId=2025-02-25

在这里插入图片描述

一开始解题思路

暴力解决法

我奔着先从简单的写法做起,之后再想办法进行改进,心里已经预料到会出现超出时间限制的报错。

class Allocator:

    def __init__(self, n: int):
        self.capacity = [0]*n
        self.size = n
        
    def allocate(self, size: int, mID: int) -> int:
        cur = 0
        while cur + size <= self.size:
            #检查当前窗口内是否全部可用
            if all(self.capacity[cur+i]==0 for i in range(size)):
                for i in range(size):
                    self.capacity[cur + i] = mID
                return cur
            else:
                cur += 1
        return -1
            
    def freeMemory(self, mID: int) -> int:
        count = 0
        for i in range(self.size):
            if self.capacity[i] == mID:
                self.capacity[i] = 0
                count = count + 1
        return count

毫无疑问,一脚就被力扣踢死了,出现超时报错(┭┮﹏┭┮)。

开始改进

分析哪些地方最为繁重

  • 经过分析,主要集中在allocate函数中,循环太多浪费时间

尝试改进方案

  • 想不出来(doge
  • 查看官方题解(模拟),恍然大悟
class Allocator:

    def __init__(self, n: int):
        self.n = n
        self.memory = [0] * n

    def allocate(self, size: int, mID: int) -> int:
        count = 0
        for i in range(self.n):
            if self.memory[i]:
                count = 0
            else:
                count += 1
                if count == size:
                    for j in range(i - count + 1, i + 1):
                        self.memory[j] = mID
                    return i - count + 1
        return -1

    def freeMemory(self, mID: int) -> int:
        count = 0
        for i in range(self.n):
            if self.memory[i] == mID:
                count += 1
                self.memory[i] = 0
        return count

复杂度分析

  • 我的写法:由于每次发现当前窗口不是0时都得重新开始遍历一遍size,所以时间复杂度是O(n*size),空间复杂度为O(1)
  • 官方写法:遍历一遍数组,发现满足size个空位才开始分配内容,所以时间复杂度是O(n),空间复杂度为O(1)

感悟

  • 哈哈哈,还是思考得不到位呢!((:з」∠),居然没想到这么简单的方法,揪着字典啥的方向去思考如何降低时间复杂度了。
  • 就这样吧,今天也算是打开完毕了。共勉,继续加油

相关文章:

  • 在linux中利用conda安装blast
  • openssh9.9p2部分Linux操作系统的rpm包
  • Spring boot中的@ConfigurationProperties注解
  • 完全背包问题
  • SQL注入(order by,limit),seacms的报错注入以及系统库的绕过
  • deepseek部署:ELK + Filebeat + Zookeeper + Kafka
  • [C++][cmake]使用C++部署yolov12目标检测的tensorrt模型支持图片视频推理windows测试通过
  • LUCEDA IPKISS Tutorial 81:通过参数函数定义形状
  • Spring Cloud源码 - Eureka源码原理分析
  • 17142弹珠堆放
  • ROS的action通信——实现阶乘运算(三)
  • echarts记录(柱状、折线、环形饼图,双柱,日期组件封装)
  • 【洛谷入门赛】B4018 游戏与共同语言
  • spring MVC执行流程
  • xss-lab
  • python与C系列语言的差异总结(3)
  • 《论区块链技术及应用》审题技巧 - 系统架构设计师
  • smolagents学习笔记系列(五)Tools-in-depth-guide
  • 每日一题-设计内存分配器;详细分析思路以及多解法
  • 如何防止 Docker 注入了恶意脚本
  • 建设招聘网站/b站网页入口
  • pub域名怎么做网站/郑州网站制作公司
  • 微网站建设高端网站定制/网站推广途径和推广要点有哪些?
  • 用html5做网站百度经验/域名查询注册商
  • 搭建高端网站/uc浏览器网页版入口
  • 手机app 网站/seo优化顾问