lintcode:Product of Array Exclude Itself
来源:互联网 发布:北京平均工资 知乎 编辑:程序博客网 时间:2024/06/06 19:29
Given an integers array A.
Define B[i] = A[0] * … * A[i-1] * A[i+1] * … * A[n-1], calculate B WITHOUT divide operation.
Example
For A = [1, 2, 3], return [6, 3, 2].
1.提交1
class Solution {public: /** * @param A: Given an integers array A * @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1] */ vector<long long> productExcludeItself(vector<int> &nums) { // write your code here vector<long long> res; for(int i=0;i<nums.size();i++){ long long product=1; for(int j=0;j<nums.size();j++){ if(j!=i){ product*=nums[j]; } } res.push_back(product); } return res; }};
AC时间是62ms.时间复杂度O(n^2)
2.提交2
class Solution {public: /** * @param A: Given an integers array A * @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1] */ vector<long long> productExcludeItself(vector<int> &nums) { // write your code here int n=nums.size(); long long left[n]; long long right[n]; left[0]=1; for(int i=1;i<n;i++){ left[i]=left[i-1]*nums[i-1]; } right[n-1]=1; /*for(int i=0;i<n-1;i++){ right[i]=right[i+1]*nums[i+1]; }*/ for(int i=n-2;i>=0;i--){ right[i]=right[i+1]*nums[i+1]; } vector<long long> res; for(int i=0;i<n;i++){ res.push_back(left[i]*right[i]); } return res; }};
AC时间12ms。空间复杂度O(N),时间复杂度O(n)
左右搜索
0 0
- Lintcode - Product of Array Exclude Itself
- lintcode:Product of Array Exclude Itself
- [Lintcode]Product of Array Exclude Itself
- Product of Array Exclude Itself
- Product of Array Exclude Itself
- Product of Array Exclude Itself
- #50 Product of Array Exclude Itself
- 【LintCode】Product of Array Exclude Itself 数组剔除元素后的乘积
- Lintcode50 Product of Array Exclude Itself solution 题解
- 50.Product of Array Exclude Itself-数组剔除元素后的乘积(容易题)
- 238.[LeetCode]Product of Array Except itself
- 238.[LeetCode]Product of Array Except itself
- [LintCode]Count of Smaller Number before itself
- 88-Product of Array
- get product of array
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- UI - SendValue
- php生成zip压缩文件的方法,支持文件和压缩包路径查找
- Javascript基础(二)
- 再战传世推广文本(请复制下面红色字体部分)
- 百练oj 2757 最长上升子序列
- lintcode:Product of Array Exclude Itself
- PostgreSQL OID 源码分析
- Depth Buffer
- Oracle多粒度锁机制的总结
- 我的Java学习之路2——继承中的构造方法
- HTTP响应头信息和请求头信息详解
- pg_basebackup 不备份哪些文件
- [转]高可用保证消息绝对顺序消费的BROKER设计方案
- 嵌入式系统编程之软件架构