-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProductOfArrayExceptSelf.java
55 lines (48 loc) · 1.37 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
public class ProductOfArrayExceptSelf {
// my solution _ O(n)
public int[] productExceptSelf1(int[] nums) {
int tmp = 1;
int cnt = 0;
boolean zeroFlag = false;
for (int i = 0; i < nums.length; i++) {
if(nums[i] == 0) {
cnt++;
if(cnt == 1 )
continue;
}
tmp *= nums[i];
}
if(cnt != 1)
zeroFlag = true;
if(zeroFlag) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0)
nums[i] = tmp;
else
nums[i] = tmp / nums[i];
}
}else {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0)
nums[i] = tmp;
else
nums[i] = 0;
}
}
return nums;
}
// my solution _ O(n^2) _ Time Limit Exceeded
public int[] productExceptSelf2(int[] nums) {
int[] answer = new int[nums.length];
for (int i = 0; i < answer.length; i++)
answer[i] = 1;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (i == j)
continue;
answer[i] *= nums[j];
}
}
return answer;
}
}