diff options
author | Michael Hunteman <michael@michaelted.xyz> | 2022-09-22 10:14:04 -0500 |
---|---|---|
committer | Michael Hunteman <michael@michaelted.xyz> | 2022-09-22 10:14:04 -0500 |
commit | 6522012065712fb0ece31bff9ff10b38a83b10e1 (patch) | |
tree | 743f3c13d08be9f60bad57b74e7a1fe7cc675e89 /ProductExceptSelf.java |
Initial commit
Diffstat (limited to 'ProductExceptSelf.java')
-rw-r--r-- | ProductExceptSelf.java | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/ProductExceptSelf.java b/ProductExceptSelf.java new file mode 100644 index 0000000..3b56f11 --- /dev/null +++ b/ProductExceptSelf.java @@ -0,0 +1,31 @@ +import java.lang.*; +import java.util.*; + +class ProductExceptSelf { + public static int[] product(int[] nums) { + int[] left = new int[nums.length]; + int[] right = new int[nums.length]; + left[0] = 1; + right[nums.length - 1] = 1; + + int s = 1; + int e = nums.length - 2; + while (s <= nums.length && e >= 0) { + left[s] = left[s - 1] * nums[s - 1]; + right[e] = right[e + 1] * nums[e + 1]; + s++; + e--; + } + + int[] res = new int[nums.length]; + for (int i = 0; i < nums.length; i++) + res[i] = left[i] * right[i]; + + return res; + } + + public static void main(String[] args) { + int[] nums = {-1, 1, 0, -3, 3}; + System.out.println(Arrays.toString(product(nums))); + } +} |