Skip to content

Commit ff0b585

Browse files
committed
LIS 추가
1 parent b8ab2d0 commit ff0b585

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
6+
class `longest-increasing-subsequence` {
7+
8+
fun lengthOfLIS(nums: IntArray): Int {
9+
return usingBinarySearch(nums)
10+
}
11+
12+
/**
13+
* 이전 최장 수열 길이를 재사용한다.
14+
* TC: O(n^2), SC: O(n)
15+
*/
16+
private fun usingDP(nums: IntArray): Int {
17+
val dp = IntArray(nums.size) { 1 }
18+
19+
for (i in 1 until nums.size) {
20+
for (j in 0 until i) {
21+
if (nums[i] > nums[j] && dp[i] < dp[j] + 1) {
22+
dp[i] = dp[j] + 1
23+
}
24+
}
25+
}
26+
27+
return dp.max()
28+
}
29+
30+
/**
31+
* 최장 수열을 직접 갱신한다.
32+
* TC: O(n * log n), SC: O(n)
33+
*/
34+
private fun usingBinarySearch(nums: IntArray): Int {
35+
36+
fun binarySearch(list: List<Int>, number: Int): Int {
37+
var (low, high) = 0 to list.size - 1
38+
39+
while (low <= high) {
40+
val mid = (low + high) / 2
41+
if (list[mid] == number) {
42+
return mid
43+
} else if (list[mid] < number) {
44+
low = mid + 1
45+
} else {
46+
high = mid - 1
47+
}
48+
}
49+
return low
50+
}
51+
52+
val result = mutableListOf<Int>()
53+
54+
for (num in nums) {
55+
if (result.isEmpty() || result.last() < num) {
56+
result.add(num)
57+
} else {
58+
result[binarySearch(result, num)] = num
59+
}
60+
}
61+
62+
return result.size
63+
}
64+
65+
@Test
66+
fun name() {
67+
// lengthOfLIS(intArrayOf(10,9,2,5,3,7,101,18)) shouldBe 4
68+
// lengthOfLIS(intArrayOf(0,1,0,3,2,3)) shouldBe 4
69+
// lengthOfLIS(intArrayOf(0,1,2,3,4,5,6,7)) shouldBe 8
70+
lengthOfLIS(intArrayOf(4,10,4,3,8,9)) shouldBe 3
71+
}
72+
}

0 commit comments

Comments
 (0)