Skip to content

Commit 6f50c5e

Browse files
committed
자기자신을 제외한 모든 배열 요소의 곱 리턴
1 parent b01b565 commit 6f50c5e

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

ProductOfArrayExceptSelf.java

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
}

0 commit comments

Comments
 (0)