Skip to content

Instantly share code, notes, and snippets.

@IngeFrodo
Last active April 15, 2020 18:05
Show Gist options
  • Save IngeFrodo/3d6ccae7de4cbaabb236a9f32a193a67 to your computer and use it in GitHub Desktop.
Save IngeFrodo/3d6ccae7de4cbaabb236a9f32a193a67 to your computer and use it in GitHub Desktop.
class ProductOfArrayExceptSelf {
public int[] productExceptSelf(int[] nums) {
if (nums.length < 2) {
return nums;
}
int[] products = new int[nums.length];
int factor = 1;
for (int i = nums.length - 1; i >= 0; i--) {
products[i] = factor * nums[i];
factor = products[i];
}
factor = 1;
for (int i = 0; i < nums.length - 1; i++) {
products[i] = factor * products[i + 1];
factor *= nums[i];
}
products[products.length - 1] = factor;
return products;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment