当前位置:网站首页>21 -- 除自身以外数组的乘积
21 -- 除自身以外数组的乘积
2022-07-22 21:25:00 【JH_Cao】
1. 题目
给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。
题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。
请不要使用除法,且在 O(n) 时间复杂度内完成此题。
示例 1:
输入: nums = [1,2,3,4]
输出: [24,12,8,6]
示例 2:
输入: nums = [-1,1,0,-3,3]
输出: [0,0,9,0,0]
简单来说,就是下面的意思:
- 思路
前缀积 * 后缀积
前缀积:
后缀积:
相乘:
代码:
func productExceptSelf(_ nums: [Int]) -> [Int] {
let cnt = nums.count
var LeftArr: [Int] = [Int](repeating: 1, count: cnt)
var RightArr: [Int] = [Int](repeating: 1, count: cnt)
for i in 1..<cnt {
LeftArr[i] = LeftArr[i - 1] * nums[i - 1]
}
for i in (0..<cnt - 1).reversed() {
RightArr[i] = RightArr[i + 1] * nums[i + 1]
}
var res = [Int]()
for i in 0..<cnt {
res.append(LeftArr[i] * RightArr[i])
}
return res
}
边栏推荐
- Interpretation of URL structure
- 局域网SDN技术硬核内幕 7 从二层到大二层
- 驱动页面性能优化的3个有效策略
- Part I sourcetree installation
- Inside the hard core of LAN SDN technology - evpn implementation of 16 three from thing to person user roaming in the park
- FTXUI基础笔记(hello world)
- 《postgresql指南--内幕探索》第一章 数据库集簇、数据库和数据表
- 大厂底层必修:“应用程序与 AMS 的通讯实现”
- 无代码生产新模式探索
- Application of workflow engine in vivo marketing automation
猜你喜欢
随机推荐
[untitled] share an API Gateway project developed based on ABP vNext
【开发技术】SpingBoot数据库与持久化技术,JPA,MongoDB,Redis
Small program completion work wechat campus second-hand book trading small program graduation design finished product (2) small program function
A web server where browser users access server files
一文深入浅出理解国产开源木兰许可系列协议
自定义flink es source
Implementation of remove function
Wechat hotel reservation applet graduation project (8) graduation project thesis template
Talk about 12 business scenarios of concurrent programming
Wechat hotel reservation applet graduation project (6) opening defense ppt
LAN SDN technology hard core insider 5 implementation of virtualized network
局域网SDN技术硬核内幕 4 从计算虚拟化到网络虚拟化
Wechat campus second-hand book trading applet graduation design finished product (4) opening report
景联文科技提供3D点云-图像标注服务
Alibaba Cloud Security Center's best practices for vulnerability repair
Classes et objets (1)
《postgresql指南--内幕探索》第二章 进程与内存架构
LAN SDN hard core technology insider 19 unite all forces that can be united
对比学习下的跨模态语义对齐是最优的吗?---自适应稀疏化注意力对齐机制 IEEE Trans. MultiMedia
【刷题记录】18. 四数之和








