Given an array of numbers, replace each number with the
product of all the numbers in the array except the number itself *without* using divisionhttps://www.glassdoor.com/Interview/Given-an-array-of-numbers-replace-each-number-with-the-product-of-all-the-numbers-in-the-array-except-the-number-itself-w-QTN_9132.htm
The key to this solution is construct the accessory arrays which assists the solution. Here are the code
Recursive way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int[] products(int[] nums){ | |
int[] products = new int[nums.length]; | |
productRec(nums, products, 0); | |
return products; | |
} | |
public static int productRec(int[] nums, int[] products, int i){ | |
if(i==nums.length-1) | |
return 1; | |
products[i] = (i==0?1:products[i-1] * nums[i-1]); | |
int p = productRec(nums, products, i+1) * nums[i+1]; | |
products[i] = products[i] * p; | |
return p; | |
} |
Iterative way:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int[] product(int[] nums){ | |
int len = nums.length; | |
int[] result = new int[len]; | |
result[0] = 1; | |
for(int i=1; i<len; i++){ | |
result[i] = result[i-1] * nums[i-1]; | |
} | |
int p = 1; | |
for(int i=len-2; i>=0; i--){ | |
p = p * nums[i+1]; | |
result[i] = result[i] * p; | |
} | |
return result; | |
} |
No comments:
Post a Comment