Skip to content

Commit 443405b

Browse files
committed
Solution for Product of Array Except Self #239
์žŠ์ง€๋ง์ž ๊ฐœํ–‰๋ฌธ์ž
1 parent 83ab2d0 commit 443405b

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import java.util.Arrays;
2+
3+
class Solution {
4+
// TC : O(n)
5+
// SC : O(n)
6+
public int[] productExceptSelf(int[] nums) {
7+
/**
8+
* Approach:
9+
* 1. Calculate the product of all non-zero elements
10+
* 2. Count how many zeros exist in the array.
11+
* 3. Handle three cases:
12+
* - If there are more than one zero, all results are 0.
13+
* - If there is exactly one zero,
14+
* only the index with 0 gets the total product; others are 0.
15+
* - If there is no zero, each result is totalProduct / nums[i].
16+
*/
17+
int zeroCount = 0;
18+
19+
for (int n : nums) {
20+
if (n == 0) {
21+
zeroCount++;
22+
}
23+
if (zeroCount > 1) {
24+
break;
25+
}
26+
}
27+
28+
if (zeroCount > 1) {
29+
return new int[nums.length];
30+
}
31+
32+
int production = Arrays.stream(nums).filter((n) -> {
33+
return n != 0;
34+
}).reduce(1, (a, b) -> a * b);
35+
36+
if (zeroCount == 1) {
37+
return Arrays.stream(nums).map((n) -> {
38+
if (n == 0) {
39+
return production;
40+
}
41+
return 0;
42+
}).toArray();
43+
}
44+
45+
return Arrays.stream(nums).map((n) -> {
46+
return production / n;
47+
}).toArray();
48+
}
49+
}

0 commit comments

Comments
ย (0)