-
Notifications
You must be signed in to change notification settings - Fork 1
/
6thJune(V).java
106 lines (83 loc) · 2.63 KB
/
6thJune(V).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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
public class ProOfarrayExceftitself {
// naive -- bad approach TC = O(n^2) and SC = O(n)
// error time limit exceeded for array which have large input
static int[] productExceptSelf1(int[] nums) {
int n = nums.length;
int [] newarr = new int[n];
for(int i =0; i<n;i++){
int product = 1;
for(int j = 0; j<n; j++){
if(j!=i){
product*=nums[j];
}
}
newarr[i] = product;
}
return newarr;
}
// simple approach TC = O(n)... SC = O(n)
// algo -
// 1- find the product of all numbers inside the array
// 2- later divide that product with array element and store it in new array
// but single 0 and more than two zeres would create some problem... handled in below code
static int[] productExceptSelf2(int[] nums){
int productfornum = 1;
int productforzero = 1;
int n = nums.length;
int[] res = new int[n];
// counting if zeroes are more than 1.... if there are more than 1 zeroes in array the result will be 0
int zeroCount = 0;
for(int i =0; i<n; i++){
if(nums[i]==0){
zeroCount+=1;
}
}
if(zeroCount>1){
return res;
}
// for nums
for(int i =0; i<n; i++){
productfornum*=nums[i];
}
// if single 0 of the array encountered
for(int i =0; i<n; i++){
if(nums[i]==0){
continue;
}
else{
productforzero*=nums[i];
}
}
// now dividing the product with the array elements
for(int i=0; i<n; i++){
if(nums[i]==0){
res[i]=productforzero;
}
else{
res[i]=productfornum/nums[i];
}
}
return res;
}
// leetcode discussion --- still didn't got this wtf he done ===============================
static int[] productExceptSelf3(int[] nums){
int[] result = new int[nums.length];
for (int i = 0, tmp = 1; i < nums.length; i++) {
result[i] = tmp;
tmp *= nums[i];
}
for (int i = nums.length - 1, tmp = 1; i >= 0; i--) {
result[i] *= tmp;
tmp *= nums[i];
}
return result;
}
public static void main(String[] args) {
int[] arr = {0,0};
// int[] res = productExceptSelf(arr);
int[] res = productExceptSelf2(arr);
for(int x : res){
System.out.print(x+",");
}
}
}