File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments