Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Blog
Product of Array Except Self
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; /* Input: [1,2,3,4] Output: [24,12,8,6] */ class Rextester { public static void main(String args[]) { System.out.println("Hello, World!"); int[] ans = productExceptSelf_constantSpace(new int[]{3,5,2,4,3}); for(int i:ans) System.out.print(i+" "); } public static int[] productExceptSelf_constantSpace(int[] nums){ //create ans array. Start with product of left elements int[] ans = new int[nums.length]; ans[0]=1; for(int i=1;i<nums.length;i++){ ans[i] = ans[i-1]*nums[i-1]; } //calculate product of right elements and store the answers in ans array directly int mul = 1; for(int j=nums.length-1;j>=0;j--){ ans[j] = ans[j]*mul; mul *= nums[j]; } return ans; } public static int[] productExceptSelf(int[] nums) { //create an array for product of all elements to the left int[] l = new int[nums.length]; l[0] = 1; for(int i=1;i<nums.length;i++){ l[i] = l[i-1]*nums[i-1]; } //create an array for product of all elements to the right int[] r = new int[nums.length]; r[nums.length-1] = 1; for(int j = nums.length-2;j>=0;j--){ r[j] = r[j+1]*nums[j+1]; } //create answer array int[] ans = new int[nums.length]; for(int k=0;k<nums.length;k++){ ans[k] = l[k]*r[k]; } return ans; } }
run
|
edit
|
history
|
help
0
Please
log in
to post a comment.
Java: If, Else, While, litle program
sfr
Find Median in Large File of Integers
1.5
variable1
doubt
checkingWord
jsis
LeetCode 121 - Best time to buy and sell stock - O(n) solution
Eckhart generator with real id
Please log in to post a comment.