-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProductOfArrayExceptSelf.java
58 lines (53 loc) · 1.55 KB
/
ProductOfArrayExceptSelf.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
public class ProductOfArrayExceptSelf {
public static void main(String[] args) {
System.out.println("Product: "+productOfArrayExceptSelf(new int[]{1,2,3,4}));
System.out.println("Product: " + productOfArrayExceptSelf(new int[]{-1, 1, 0, -3, 3}));
}
public static int[] productOfArrayExceptSelf(int[] nums) {
int n = nums.length;
int[] answer = new int[n];
for(int i = 0; i < n; i++){
answer[i] = 1;
}
int leftProduct = 1;
for(int i = 0; i<n; i++){
answer[i] = leftProduct;
leftProduct *= nums[i];
}
int rightProduct = 1;
for(int i = n -1; i>=0; i--){
answer[i] *= rightProduct;
rightProduct *= nums[i];
}
return answer;
//1,2,3,4
// int[] result = new int[array.length];
// long product = 1;
// boolean zero = false;
// for (int i = 0; i < array.length; i++) {
//
// for (int j = 0; j < array.length; j++) {
// if (j == i) continue;
// if (array[j] == 0) {
// zero = true;
// break;
// }else{
// product *= array[j];
// }
//
// }
// result[i] = zero ? 0 : Math.toIntExact(product);
// product=1;
// zero = false;
//
//
// }
//
// return result;
}
}