Skip to content

Commit eca2f02

Browse files
committed
feat(leetcode/238): Product of Array Except Self (Medium)
1 parent 7aef46c commit eca2f02

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

product-of-array-except-self/renovizee.java

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,45 @@
22

33
// tag renovizee 2week
44
// https://github.com/DaleStudy/leetcode-study/issues/239
5-
// https://leetcode.com/problems/product-of-array-except-self/
5+
// https://leetcode.com/problems/product-of-array-except-self/ #238 #Medium
66
class Solution {
77
// Solv1 :
88
// 시간복잡도 : O(n)
99
// 공간복잡도 : O(n)
1010
public int[] productExceptSelf(int[] nums) {
1111

12+
boolean isZero = false;
13+
int zeroIndex = 0;
14+
15+
int productExceptZero = 1;
16+
for (int i = 0; i < nums.length; i++) {
17+
if (nums[i] == 0) {
18+
if (isZero) { // zero가 2개면 모든 원소가 0임.
19+
return new int[nums.length];
20+
}
21+
zeroIndex = i;
22+
isZero = true;
23+
} else {
24+
productExceptZero *= nums[i];
25+
}
26+
}
27+
28+
int[] result = new int[nums.length];
29+
for (int i = 0; i < nums.length; i++) {
30+
if (isZero) {
31+
if (i != zeroIndex) {
32+
result[i] = 0;
33+
} else {
34+
result[i] = productExceptZero;
35+
}
36+
} else {
37+
result[i] = productExceptZero / nums[i];
38+
}
39+
40+
}
41+
return result;
1242
}
43+
1344
}
1445

1546
//-------------------------------------------------------------------------------------------------------------

0 commit comments

Comments
 (0)