File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode_study
2
+
3
+ /* *
4
+ * 주어진 숫자 배열에서 두 개의 숫자를 더해 Target을 만들 수 있는 배열의 Index를 구하는 문제
5
+ * 조합을 사용해 문제 해결
6
+ * 시간 복잡도: O(n^2)
7
+ * -> 두 번의 순회를 통해 모든 경우의 수를 계산하는 경우
8
+ * 공간 복잡도: O(1)
9
+ * -> 결과를 저장하는 result, 배열의 index를 가리키는 indices는 두 개의 값을 담기 때문에 O(1)
10
+ */
11
+ fun twoSum (nums : IntArray , target : Int ): IntArray {
12
+ val result = IntArray (2 )
13
+ val k = 2
14
+ val maxSize = nums.size
15
+ val indices = IntArray (k)
16
+ for (i in 0 until k ) {
17
+ indices[i] = i
18
+ }
19
+
20
+ while (indices[k- 1 ] < maxSize) {
21
+ if (nums[indices[0 ]] + nums[indices[1 ]] == target) {
22
+ result[0 ] = indices[0 ]
23
+ result[1 ] = indices[1 ]
24
+ return result
25
+ }
26
+
27
+ var i = k - 1
28
+ while (i >= 0 && indices[i] == i + maxSize - k) {
29
+ i--
30
+ }
31
+
32
+ if (i >= 0 ) {
33
+ indices[i]++
34
+ for (j in i + 1 until k) {
35
+ indices[j] = indices[j - 1 ] + 1
36
+ }
37
+ } else {
38
+ break
39
+ }
40
+ }
41
+ return result
42
+ }
You can’t perform that action at this time.
0 commit comments