Skip to content

Commit 9973c72

Browse files
author
이연수
committed
product of array except self
1 parent ea9aa53 commit 9973c72

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package leetcode_study
2+
3+
/*
4+
* 주어진 배열에서 자신 요소를 제외한 나머지 요소의 곱한 배열을 구하는 문제
5+
* 문제에세 O(n)의 시간 복잡도를 요구하였으나 방법이 떠오르지 않아 고민 후 정답 참조.
6+
* 기준 요소를 중심으로 왼쪽의 총 곱, 오른쪽의 총 곱을 진행하게 되었을 때, 문제를 O(n)의 시간 복잡도로 해결할 수 있음.
7+
* 시간 복잡도: O(n^2)
8+
* 공간 복잡도: O(n)
9+
* */
10+
fun productExceptSelf00(nums: IntArray): IntArray {
11+
val result = mutableListOf<Int>()
12+
13+
for (i in nums.indices) {
14+
var temp = 1
15+
for (j in nums.indices) {
16+
if (i == j) continue
17+
temp *= nums[j]
18+
}
19+
result.add(temp)
20+
}
21+
return result.toIntArray()
22+
}
23+
24+
/*
25+
* 시간 복잡도: O(n)
26+
* 공간 복잡도: O(n)
27+
* */
28+
fun productExceptSelf01(nums: IntArray): IntArray {
29+
val result = IntArray(nums.size)
30+
31+
var leftProduct = 1
32+
for (i in nums.indices) {
33+
result[i] = leftProduct
34+
leftProduct = leftProduct * nums[i]
35+
}
36+
37+
var rightProduct = 1
38+
for (i in nums.indices.reversed()) {
39+
result[i] = result[i] * rightProduct
40+
rightProduct = rightProduct * nums[i]
41+
}
42+
return result
43+
}

0 commit comments

Comments
 (0)