Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- */
- Given an array nums of n integers where n > 1,
- return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
- Example:
- Input: [1,2,3,4]
- Output: [24,12,8,6]
- Note: Please solve it without division and in O(n).
- */
- class Solution {
- public int[] productExceptSelf(int[] nums) {
- if (nums.length < 2) {
- throw new IllegalArgumentException("Array must have more than 2 numbers to compute product");
- }
- int[] productsBeforeIndex = getProductsBeforeIndex(nums);
- int[] productsAfterIndex = reverseArray(getProductsBeforeIndex(reverseArray(nums)));
- return productsOfTwoArrays(productsBeforeIndex, productsAfterIndex);
- }
- public int[] getProductsBeforeIndex(int[] a) {
- int[] res = new int[a.length];
- res[0] = 1;
- for (int i = 1; i < a.length; i++) {
- res[i] = res[i - 1] * a[i - 1];
- }
- return res;
- }
- public int[] reverseArray(int[] a) {
- for (int i = 0; i < a.length / 2; i++) {
- int temp = a[i];
- a[i] = a[a.length - 1 - i];
- a[a.length - 1 - i] = temp;
- }
- return a;
- }
- public int[] productsOfTwoArrays(int[] a1, int[] a2) {
- int[] res = new int[a1.length];
- for (int i = 0; i < a1.length; i++) {
- res[i] = a1[i] * a2[i];
- }
- return res;
- }
- }
Add Comment
Please, Sign In to add comment