238. Product of Array Except Self

网友投稿 630 2022-09-04

238. Product of Array Except Self

238. Product of Array Except Self

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.)

class Solution { public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] res = new int[n]; int[] fwd = new int[n], bwd = new int[n]; fwd[0] = 1; bwd[n - 1] = 1; for (int i = 1; i < n; ++i) { fwd[i] = fwd[i - 1] * nums[i - 1]; } for (int i = n - 2; i >= 0; --i) { bwd[i] = bwd[i + 1] * nums[i + 1]; } for (int i = 0; i < n; ++i) { res[i] = fwd[i] * bwd[i]; } return

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:深度剖析|数据库生产常用架构方案(库存系统架构设计)
下一篇:304. Range Sum Query 2D - Immutable
相关文章

 发表评论

暂时没有评论,来抢沙发吧~