Skip to content

Instantly share code, notes, and snippets.

@hsaputra
Created November 9, 2018 06:05
Show Gist options
  • Save hsaputra/9fea5013eab51d45d04aafc050bc8ff8 to your computer and use it in GitHub Desktop.
Save hsaputra/9fea5013eab51d45d04aafc050bc8ff8 to your computer and use it in GitHub Desktop.
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] results = new int[nums.length];
int[] left = new int[nums.length];
Arrays.fill(left, 1);
// [1, 2, 3, 4]
// [1, 1, 2, 6]
for (int i = 1; i < nums.length; i++) {
left[i] = left[i - 1] * nums[i - 1];
// System.out.println("Left i " + i + " is " + left[i]);
}
int[] right = new int[nums.length];
Arrays.fill(right, 1);
// [1, 2, 3, 4]
// [24 , 12, 4, 1]
for (int j = (nums.length - 2) ; j >= 0; j--) {
right[j] = right[j + 1] * nums[j + 1];
//System.out.println("Right j " + j + " is " + right[j]);
}
// multiply lefyt and right
for (int k = 0; k < nums.length ; k++) {
System.out.println("Left k " + k + " is " + left[k]);
System.out.println("Right k " + k + " is " + right[k]);
results[k] = left[k] * right[k];
}
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment