50.Product of Array Exclude Itself-数组剔除元素后的乘积(容易题)
来源:互联网 发布:耽美网络剧资源百度云 编辑:程序博客网 时间:2024/06/07 06:41
数组剔除元素后的乘积
题目
给定一个整数数组A。
定义B[i] = A[0] * … * A[i-1] * A[i+1] * … * A[n-1], 计算B的时候请不要使用除法。
样例
给出A=[1, 2, 3],返回 B为[6, 3, 2]
题解
1.暴力解法
public class Solution { /** * @param A: Given an integers array A * @return: A Long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1] */ public ArrayList<Long> productExcludeItself(ArrayList<Integer> A) { // write your code ArrayList<Long> result = new ArrayList<Long>(); for (int i=0;i<A.size();i++) { long temp = 1; for (int j=0;j<A.size();j++) { if (j!=i) { temp*=(long)A.get(j).intValue(); } } result.add(temp); } return result; }}
2.用空间换时间O(n)。
开辟两个数组,通过遍历原数组的两边得到存储某个数左右两边的乘积,然后将这两个数组对应位相乘即可。
public class Solution { /** * @param A: Given an integers array A * @return: A Long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1] */ public ArrayList<Long> productExcludeItself(ArrayList<Integer> A) { ArrayList<Long> result = new ArrayList<Long>(); int n = A.size(); long[] arrL = new long[n]; long[] arrR = new long[n]; arrL[0] = 1; for (int i=1;i<n;i++) { arrL[i] = arrL[i-1] * A.get(i-1); } arrR[n-1] = 1; for (int i=n-2;i>=0;i--) { arrR[i] = arrR[i+1] * A.get(i+1); } for (int i=0;i<n;i++) { result.add(arrL[i] * arrR[i]); } return result; }}
Last Update 2016.8.28
0 0
- 50.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
- Lintcode - Product of Array Exclude Itself
- lintcode:Product of Array Exclude Itself
- [Lintcode]Product of Array Exclude Itself
- #50 Product of Array Exclude Itself
- Lintcode50 Product of Array Exclude Itself solution 题解
- 数组剔除元素后的乘积
- 题目:数组剔除元素后的乘积
- LintCode 数组剔除元素后的乘积
- (50)数组剔除元素后的乘积
- LintCode_数组剔除元素后的乘积
- 数组剔除元素后的乘积
- lintcode ----数组剔除元素后的乘积
- 数组剔除元素后的乘积
- android开关控件使用(一)
- 读《About Face 4 交互设计精髓》15
- post 请求与get请求的区别?
- 依赖属性与Binding
- Spring-Session配置,底层数据库使用Redis或Mysql
- 50.Product of Array Exclude Itself-数组剔除元素后的乘积(容易题)
- php模板引擎smaty之介绍
- 自定义Dialog
- 文章标题
- javascript_解析json对象
- Happy Number
- 关于Ubuntu安装java设置环境变量的问题
- 牛客网答题笔记--构造队列
- HTML使用总结