Product of Array Except Self
来源:互联网 发布:首份网络主播黑名单 编辑:程序博客网 时间:2024/04/30 09:57
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]
.
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
以后补充下O(1)空间复杂度的解法。
思路是左边扫一次,右边骚一次,分别把当前数字的左边的乘积结果保存在一个数组,然后右侧扫一遍,保存右侧的乘积结果,然后输出。
代码:
public int[] productExceptSelf(int[] nums) { if(nums == null || nums.length == 0) return new int[0]; int [] left = new int[nums.length]; left[0] = 1; for(int i=1;i<nums.length;i++){ left[i] = left[i-1]*nums[i-1]; } int []right = new int[nums.length]; right[nums.length-1] = 1; for(int i=nums.length-2;i>=0;i--){ right[i] = right[i+1] * nums[i+1]; left[i] *= right[i]; } return left; }
再简化一些可以只使用一个变量保存中间结果:
0 0
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- (记录合并)union和union all 的区别
- 1123. Is It a Complete AVL Tree (30)
- Mongodb自己封装的工具类
- 2、往数组int array[] = {1,2,3,4,5,6,7}第3个位置插入一个数8,最后的结果应该为{1,2,3,8,4,5,6,7}
- 使用WITH AS提高性能简化嵌套SQL
- Product of Array Except Self
- 浏览器中“JavaScript解析器”工作原理_优就业
- 静态java代码检查工具-findbug使用简介
- 修改XML文档的例子
- 2016年12月13日
- Android—WebView简单使用
- 一个可以左滑删除的完整购物车DelSlideExpandableListView
- 集合、数域、线性空间、n维欧式空间的概念
- oracle数据类型及SQL语言