LeetCode-Product of Array Except Self
来源:互联网 发布:数据化人生 编辑:程序博客网 时间:2024/05/07 19:06
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.)
自己没倒腾出来,确实挺难想的,但是当得知其中的奥秘时,不时感觉此算法真是妙。
题目大致意思就是求一个output数组,output[i]为数组nums数组除nums[i]之外数字的所有乘积,比如:
Input : [1, 2, 3, 4, 5]Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)] = [120, 60, 40, 30, 24]
要求不用除法,时间复杂度O(n)解题思路基于以下集合
{ 1, a[0], a[0]*a[1], a[0]*a[1]*a[2], }{ a[1]*a[2]*a[3], a[2]*a[3], a[3], 1, }
很显然,这两个集合都可以在O(n)的时间复杂度求得,之后两个集合对应位置相乘即为所得。是不是很妙?空间复杂度为O(n)的实现:
public int[] productExceptSelf(int[] nums) { int[] productBelow = new int[nums.length]; int n = 1; for (int i = 0; i < nums.length; i++) { productBelow[i] = n; n *= nums[i]; } int[] productAbove = new int[nums.length]; n = 1; for (int i = nums.length-1; i >= 0; i--) { productAbove[i] = n; n *= nums[i]; } int[] output = new int[nums.length]; for (int i = 0; i < nums.length; i++) { output[i] = productAbove[i] * productBelow[i]; } return output; }但是,如果要求是O(1)的空间复杂度呢?只需要把最后两步合二为一即可:
int[] output = new int[nums.length]; int n = 1; for (int i = 0; i < nums.length; i++) { output[i] = n; n *= nums[i]; } n = 1; for (int i = nums.length-1; i >= 0; i--) { output[i] *= n; n *= nums[i]; } return output;
0 0
- [leetcode][array] Product of Array Except Self
- 【LeetCode】237 Product of Array Except Self
- #leetcode#Product of Array Except Self
- leetcode 238: Product of Array Except Self
- [leetcode] 238.Product of Array Except Self
- [leetcode] Product of Array Except Self
- LeetCode Product of Array Except Self
- leetCode(43):Product of Array Except Self
- LeetCode Product of Array Except Self
- 【leetcode】Product of Array Except Self
- 【leetcode】Product of Array Except Self
- leetcode: Product of Array Except Self
- [leetcode] Product of Array Except Self
- [LeetCode] Product of Array Except Self
- Leetcode: Product of Array Except Self
- LeetCode 238: Product of Array Except Self
- LeetCode-Product of Array Except Self
- Leetcode #238 Product of Array Except Self
- LeetCode题解——Excel Sheet Column Title
- js倒计时代码 支持同一页面多个倒计时代码(转)
- POJ 3352 Road Construction(边双连通分量)
- uva11297 二维线段树
- shopNC分类,递归方式查询层级显示
- LeetCode-Product of Array Except Self
- ViewPager取消左右滑动切换功能
- 关于asp.net网址出现乱码问题的解决方法
- hdu4044GeoDefense 树形dp+分组背包
- 正则表达式简介及学习网址、测试网址
- PPT格式转成PDF的转换操作
- 皮肤变黑的原因
- Java图形界面事件监听处理之四种方法
- 【暑期基础】D HDU 2003 求绝对值