Skip to content

Commit 0315273

Browse files
committed
product-of-array-except-self solution
1 parent 5a9922a commit 0315273

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
/* 시간 복잡도: O(N)
3+
* - for 루프: O(N)
4+
* 공간 복잡도: O(N), answer 배열
5+
*/
6+
public int[] productExceptSelf(int[] nums) {
7+
int product = 1;
8+
int zeroCnt = 0;
9+
for (int num : nums) {
10+
if (num == 0) {
11+
zeroCnt += 1;
12+
continue;
13+
}
14+
product *= num;
15+
}
16+
17+
int[] answer = new int[nums.length];
18+
if (zeroCnt > 1) {
19+
return answer;
20+
}
21+
22+
for (int i = 0; i < nums.length; i++) {
23+
int num = nums[i];
24+
if (zeroCnt == 1) {
25+
if (num == 0) answer[i] = product;
26+
} else {
27+
answer[i] = product / num;
28+
}
29+
}
30+
return answer;
31+
}
32+
}
33+

0 commit comments

Comments
 (0)