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

[python 刷题] 238 Product of Array Except Self

[python 刷题] 238 Product of Array Except Self

题目:

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

这里题目中 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer 就很明显提示说用 prefix sum 了

另外还有就是题目要求的 O ( n ) O(n) O(n) 的时间复杂度,以及不能用除法

题目要求是获取除了自己以外的所有乘积,以题目中的案例 [1,2,3,4],它的乘积可以理解成这样的计算方式:

数组1234
prefix11126
postfix2412411
productprefix[i] * postfix[i] = 24prefix[i] * postfix[i] = 12prefix[i] * postfix[i] = 8prefix[i] * postfix[i] = 6

其中 prefix 是所有的前置乘积,postfix 是所有的后置乘积

解法如下:

class Solution:def productExceptSelf(self, nums: List[int]) -> List[int]:prefix = [1] * (len(nums) + 2)postfix = [1] * (len(nums) + 2)for i in range(2, len(prefix)):prefix[i] = prefix[i - 1] * nums[i - 2]for i in range(len(prefix) - 3, 0, -1):postfix[i] = postfix[i + 1] * nums[i]res = [1] * len(nums)for i in range(0, len(nums)):print(prefix[i + 1])res[i] = prefix[i + 1] * postfix[i + 1]return res

但是在实际写的时候发现 map index 的处理稍微麻烦了一些,所以又找了一下其他的写法,发现了一个优化的写法:

class Solution:def productExceptSelf(self, nums: List[int]) -> List[int]:res = [1] * (len(nums))for i in range(1, len(nums)):res[i] = res[i-1] * nums[i-1]postfix = 1for i in range(len(nums) - 1, -1, -1):res[i] *= postfixpostfix *= nums[i]return res

这个写法将原本的 3 pass 缩减成了 2 pass,即只有两个循环,主要是因为没有保存 postfix 这个数组,而是一边迭代一边计算 postfix

同时,prefix 的值直接存在了返回值中,跳掉了表格中下标为 0 的占位符

虽然时间和空间的大O还是一样的,不过速度和性能上确实好了不少

http://www.lryc.cn/news/169890.html

相关文章:

  • UG NX二次开发(C#)-计算直线到各个坐标系轴向的投影角度
  • C# ComboBox 和 枚举类型(Enum)相互关联
  • Linux CentOS7 tree命令
  • 软件设计模式系列之九——桥接模式
  • 构造函数的调用规则
  • 第十章:枚举类与注解
  • ChatGPT:字符串操作问题——提取包含括号的字符串中的题干内容
  • jvm中对象创建、内存布局以及访问定位
  • C基础-操作符详解
  • 时序预测 | MATLAB实现BO-BiGRU贝叶斯优化双向门控循环单元时间序列预测
  • 【深度学习实验】线性模型(五):使用Pytorch实现线性模型:基于鸢尾花数据集,对模型进行评估(使用随机梯度下降优化器)
  • ADB底层原理
  • etcd之读性能主要影响因素
  • 【Stable Diffusion】安装 Comfyui 之 window版
  • Ansys Zemax | 如何建立二向分色分光镜
  • Mybatis学习笔记8 查询返回专题
  • 【测试开发】基础篇 · 专业术语 · 软件测试生命周期 · bug的描述 · bug的级别 · bug的生命周期 · 处理争执
  • ​bing许少辉乡村振兴战略下传统村落文化旅游设计images
  • 第三十一章 Classes - 继承规则
  • 华为云HECS安装docker并安装mysql
  • MQ - 04 基础篇_存储_消息数据和元数据的存储设计
  • JavaScript:隐式转换、显示转换、隐式操作、显示操作
  • 2023全新TwoNav开源网址导航系统源码 | 去授权版
  • Android 12 源码分析 —— 应用层 六(StatusBar的UI创建和初始化)
  • 华为云ROMA Connect亮相Gartner®全球应用创新及商业解决方案峰会,助力企业应用集成和数字化转型
  • 虚拟线上发布会带来颠覆性新体验,3D虚拟场景直播迸发品牌新动能
  • Linux arm64 pte相关宏
  • MVCC:多版本并发控制案例分析(一)
  • 以数据为中心的安全市场快速增长
  • AUTOSAR汽车电子嵌入式编程精讲300篇-经典 AUTOSAR 安全防御能力的分析及改善(下)