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

Product of Array Except Self

时间:2020-01-31 10:19:39      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:contain   length   example   complex   return   The   for   element   NPU   

Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

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

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

 1 public class Solution {
 2     public int[] productExceptSelf(int[] nums) {
 3         int n = nums.length;
 4         int[] res = new int[n];
 5         res[0] = 1;
 6         for (int i = 1; i < n; i++) {
 7             res[i] = res[i - 1] * nums[i - 1];
 8         }
 9         int right = 1;
10         for (int i = n - 1; i >= 0; i--) {
11             res[i] *= right;
12             right *= nums[i];
13         }
14         return res;
15     }
16     
17     public int[] productExceptSelf(int[] nums) {
18         // Left is an array containing the left products
19         // i.e: left[i] = nums[0] * .... * nums[i-1]
20         int[] left = new int[nums.length];
21         
22         // Right is an array containing the array products
23         //i.e: right[i] = nums[i+1] * nums[i+2]  * .... * nums[len(nums) - 1]
24         int[] right = new int[nums.length];
25         
26         left[0] = 1;
27         for (int i = 1; i < nums.length; i++) {
28             left[i] = left[i-1] * nums[i-1];
29         }
30         
31         right[nums.length - 1] = 1;
32         for (int i = nums.length - 2; i >= 0; i--) {
33             right[i] = right[i+1] * nums[i+1];
34         }
35         
36         int[] product = new int[nums.length];
37         for (int i = 0; i < product.length; i++) {
38             product[i] = left[i] * right[i];
39         }
40         
41         return product;
42     }
43 }

 

Product of Array Except Self

标签:contain   length   example   complex   return   The   for   element   NPU   

原文地址:https://www.cnblogs.com/beiyeqingteng/p/12244670.html

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