LeetCode#238 Product of Array Except Self (week11)
来源:互联网 发布:linux shadow密码破解 编辑:程序博客网 时间:2024/06/06 07:40
week11
题目
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
原题地址:https://leetcode.com/problems/product-of-array-except-self/description/
解析
题意要求给定数组,求出每个元素除该元素外其他所有元素的积,但要求不使用除法且算法的时间复杂度为O(n)
下面介绍的是空间复杂度为O(n)的解法
用长度为数组长度length的vector数组存放中间计算结果及最终结果
遍历一边原数组,当遍历到第i个元素时,begin存放的是前i个元素(不包括第i个元素)的乘积,end存放的是后i个元素(不包括倒数第i个元素)的乘积,则遍历到第length-i-1的时候,end存放的是第i个元素后面所有元素的乘积,将前者的begin和后者的end相乘得到除第i个元素外其他所有元素的乘积
代码
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { int length = nums.size(); int begin = 1; int end = 1; vector<int> result(length, 1); for (int i = 0; i < length; ++i) { result[i] *= begin; begin *= nums[i]; result[length - i - 1] *= end; end *= nums[length - i - 1]; } return result; }};
阅读全文
0 0
- LeetCode#238 Product of Array Except Self (week11)
- leetcode 238: Product of Array Except Self
- LeetCode 238: Product of Array Except Self
- Leetcode #238 Product of Array Except Self
- Leetcode 238 Product of Array Except Self
- [leetcode 238]Product of Array Except Self
- LeetCode(238)Product of Array Except Self
- leetcode 238: Product of Array Except Self
- Leetcode #238 Product of Array Except Self
- [LeetCode 238] Product of Array Except Self
- leetcode 238:Product of Array Except Self
- Product of Array Except Self - LeetCode 238
- LeetCode 238 Product of Array Except Self
- 【LEETCODE】238-Product of Array Except Self
- LeetCode 238:Product of Array Except Self
- leetcode 238 Product of Array Except Self
- leetcode 238: Product of Array Except Self
- [LeetCode 238] Product of Array Except Self
- jvm编译运行(2)
- python练习题4 将mRNA翻译成蛋白质
- JS获取节点的兄弟,父级,子级元素的方法
- 【opencv】树莓派picamera+opencv人脸识别
- AlphaGo Zero原理浅析
- LeetCode#238 Product of Array Except Self (week11)
- 严蔚敏版数据结构学习笔记(4):队列
- 可视化库Matplotlib-子图
- 重装系统 Win 10 Flow
- 对FCN及反卷积的理解
- vim 配置
- 【java多线程编程核心技术】2.对象及变量的并发访问(下)-笔记总结
- 网页中文词语抓取+词云显示
- Jetty架构和实现分析