Created
August 5, 2019 16:19
-
-
Save psaitu/d1b7a6a51bf49909aaab6210f2dd424b to your computer and use it in GitHub Desktop.
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
import java.util.Arrays; | |
public class Main { | |
/** | |
* | |
* @param arr | |
* | |
* | |
* [1, 2, 3, 4] | |
* | |
* [1, 0, 0, 0] | |
* | |
* [0, 0, 0, 1] | |
* | |
* | |
* l: [1, 1, 2, 6] | |
* | |
* r: [24, 12, 4, 1] | |
* | |
* | |
* [1, 2, 3, 4] | |
* | |
* [a(0), a(1), a(2), a(3)] | |
* | |
* | |
* p: [a(1) * a(2) * a(3), a(0) * a(2) * a(3), a(0) * a(1), a(3), a(0) * a(1) * a(2)] | |
* | |
* l: [1, a(0), a(1) * a(0), a(2) * a(1) * a(0)] | |
* | |
* r: [a(1) * a(2) * a(3), a(2) * (a3), a(3), 1] | |
* | |
* | |
*/ | |
public static void productArray(int arr[]) { | |
int n = arr.length; | |
int[] left = new int[n]; | |
int[] right = new int[n]; | |
int[] product = new int[n]; | |
left[0] = 1; | |
right[n -1] = 1; | |
for(int i = 1; i < n; i++) { | |
left[i] = left[i -1] * arr[i - 1]; | |
} | |
for(int j = n - 2; j >= 0; j--) { | |
right[j] = arr[j + 1] * right[j + 1]; | |
} | |
for(int k = 0; k < n; k++) { | |
product[k] = left[k] * right[k]; | |
} | |
for(int l = 0; l < n; l++) { | |
System.out.print(product[l] + ", "); | |
} | |
} | |
public static void prodArraySpace(int[] arr) { | |
int n = arr.length; | |
int temp = 1; | |
int[] product = new int[n]; | |
for(int i = 0; i < n; i++) { | |
product[i] = 1; | |
} | |
// [1, 2, 3, 4] | |
for(int i = 0; i < n; i++) { | |
product[i] *= temp; | |
temp *= arr[i]; | |
} | |
System.out.println(Arrays.toString(product)); | |
temp = 1; | |
for(int j = n - 1; j >= 0; j--) { | |
product[j] *= temp; | |
temp *= arr[j]; | |
} | |
System.out.println(Arrays.toString(product)); | |
for(int l = 0; l < n; l++) { | |
System.out.print(product[l] + ", "); | |
} | |
} | |
public static void main(String[] args) { | |
int[] a = new int[]{1, 2, 3, 4}; | |
prodArraySpace(a); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment