File tree 1 file changed +55
-0
lines changed
1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class ProductOfArrayExceptSelf {
2
+
3
+ // my solution _ O(n)
4
+ public int [] productExceptSelf1 (int [] nums ) {
5
+ int tmp = 1 ;
6
+ int cnt = 0 ;
7
+ boolean zeroFlag = false ;
8
+
9
+ for (int i = 0 ; i < nums .length ; i ++) {
10
+ if (nums [i ] == 0 ) {
11
+ cnt ++;
12
+ if (cnt == 1 )
13
+ continue ;
14
+ }
15
+ tmp *= nums [i ];
16
+ }
17
+
18
+ if (cnt != 1 )
19
+ zeroFlag = true ;
20
+
21
+ if (zeroFlag ) {
22
+ for (int i = 0 ; i < nums .length ; i ++) {
23
+ if (nums [i ] == 0 )
24
+ nums [i ] = tmp ;
25
+ else
26
+ nums [i ] = tmp / nums [i ];
27
+ }
28
+ }else {
29
+ for (int i = 0 ; i < nums .length ; i ++) {
30
+ if (nums [i ] == 0 )
31
+ nums [i ] = tmp ;
32
+ else
33
+ nums [i ] = 0 ;
34
+ }
35
+ }
36
+ return nums ;
37
+ }
38
+
39
+
40
+ // my solution _ O(n^2) _ Time Limit Exceeded
41
+ public int [] productExceptSelf2 (int [] nums ) {
42
+ int [] answer = new int [nums .length ];
43
+ for (int i = 0 ; i < answer .length ; i ++)
44
+ answer [i ] = 1 ;
45
+
46
+ for (int i = 0 ; i < nums .length ; i ++) {
47
+ for (int j = 0 ; j < nums .length ; j ++) {
48
+ if (i == j )
49
+ continue ;
50
+ answer [i ] *= nums [j ];
51
+ }
52
+ }
53
+ return answer ;
54
+ }
55
+ }
You can’t perform that action at this time.
0 commit comments