|
1 |
| -// 풀이 |
2 |
| -// 현재 인덱스가 i 일 때, 문제에서 구하고자 하는 값은 아래와 같다. |
3 |
| -// 나의 왼쪽(i-1)부터 처음까지의 곱 * 나의 오른쪽(i+1)부터 끝까지의 곱 |
4 |
| -// leftProduct[i-1] = 왼쪽(i-1)부터 처음까지의 곱 |
5 |
| -// rightProduct[i+1] = 오른쪽(i+1)부터 끝까지의 곱 |
6 |
| -// leftProduct는 처음부터 i까지 순회하면서 구하면 된다. leftProduct[i] = leftProduct[i-1] * (나 자신 = nums[i]) |
7 |
| -// rightProduct는 끝부터 시작해서 i까지 순회하면서 구하면 된다. rightProduct[i] = rightProduct[i+1] * (나 자신 = nums[i]) |
8 |
| - |
| 1 | +// 시간 복잡도: O(n) - nums 배열의 길이 n |
| 2 | +// 공간 복잡도: O(n) - leftProduct와 rightProduct 배열을 사용 |
| 3 | +class Solution { |
9 | 4 |
|
10 |
| -// DP 를 사용하면 시간 복잡도는 O(N) |
11 |
| -// 공간 복잡도는 2개의 배열이 필요하고, 답으로 보낼 배열까지 해서 O(3*N) = O(N) |
| 5 | + public int[] productExceptSelf(int[] nums) { |
| 6 | + int[] leftProduct = new int[nums.length]; |
| 7 | + int[] rightProduct = new int[nums.length]; |
12 | 8 |
|
13 |
| -class Solution { |
14 |
| - public int[] productExceptSelf(int[] nums) { |
15 |
| - int len = nums.length; |
16 |
| - int[] leftProduct = new int[len]; |
17 |
| - int[] rightProduct = new int[len]; |
| 9 | + for (int i = 0; i < nums.length; i++) { |
| 10 | + if (i == 0) { |
| 11 | + leftProduct[i] = 1; |
| 12 | + } else { |
| 13 | + leftProduct[i] = leftProduct[i - 1] * nums[i - 1]; |
| 14 | + } |
| 15 | + } |
18 | 16 |
|
19 |
| - leftProduct[0] = nums[0]; |
20 |
| - rightProduct[len - 1] = nums[len - 1]; |
21 |
| - for (int i = 1; i < len; ++i) { |
22 |
| - leftProduct[i] = leftProduct[i - 1] * nums[i]; |
23 |
| - rightProduct[len - i - 1] = rightProduct[len - i] * nums[len - i - 1]; |
24 |
| - } |
| 17 | + for (int i = nums.length - 1; i >= 0; i--) { |
| 18 | + if (i == nums.length - 1) { |
| 19 | + rightProduct[i] = 1; |
| 20 | + } else { |
| 21 | + rightProduct[i] = rightProduct[i + 1] * nums[i + 1]; |
| 22 | + } |
| 23 | + } |
25 | 24 |
|
26 |
| - int[] result = new int[len]; |
27 |
| - result[0] = rightProduct[1]; |
28 |
| - result[len - 1] = leftProduct[len - 2]; |
29 |
| - for (int i = 1; i < len - 1; ++i) { |
30 |
| - result[i] = leftProduct[i - 1] * rightProduct[i + 1]; |
31 |
| - } |
32 |
| - return result; |
| 25 | + int[] result = new int[nums.length]; |
| 26 | + for (int i = 0; i < nums.length; i++) { |
| 27 | + result[i] = leftProduct[i] * rightProduct[i]; |
33 | 28 | }
|
| 29 | + return result; |
| 30 | + } |
34 | 31 | }
|
35 | 32 |
|
| 33 | + |
0 commit comments