码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 238. Product of Array Except Self

时间:2020-01-21 14:45:44      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:output   fun   数组   tput   var   NPU   数字   ram   leetcode   

除本身之外的数组之积。题意是给一个数组,请输出一个(应该是等长的)数组,res[i]位上存的是input数组除了i位其他所有数字的乘积。例子,

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

注意这个题不能用除法,如果用除法会很简单。思路是对于在i位上的数字,在res[i]上存住从左往右把之前每个数字相乘的乘积 * 从右向左在i之后每个数字相乘的乘积。注意左边和右边的代码稍有不同,需要多体会。

时间O(n)

空间O(n)

 1 /**
 2  * @param {number[]} nums
 3  * @return {number[]}
 4  */
 5 var productExceptSelf = function(nums) {
 6     var left = 1;
 7     var product = [];
 8     for (let num of nums) {
 9         product.push(left);
10         left = left * num;
11     }
12 
13     var right = 1;
14     for (var i = nums.length - 1; i >= 0; i--) {
15         product[i] *= right;
16         right *= nums[i];
17     }
18     return product;
19 };

[LeetCode] 238. Product of Array Except Self

标签:output   fun   数组   tput   var   NPU   数字   ram   leetcode   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12221663.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!