Skip to content

Commit 44f4a6b

Browse files
committed
longest increasing subsequence
1 parent 7b1d88b commit 44f4a6b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
dp를 활용한 방식
3+
nums의 길이 -> N
4+
시간 복잡도 : O(N)
5+
공간 복잡도 : O(N)
6+
*/
7+
class Solution {
8+
public int lengthOfLIS(int[] nums) {
9+
int[] dp =new int[nums.length];
10+
for(int i = 0; i < dp.length; i++) {
11+
for(int j = 0; j < i; j++) {
12+
if(nums[i] > nums[j]) {
13+
dp[i] = Math.max(dp[i], dp[j] + 1);
14+
}
15+
}
16+
}
17+
return Arrays.stream(dp)
18+
.max()
19+
.getAsInt() + 1;
20+
}
21+
}
22+
23+
/**
24+
이분탐색 활용한 방식
25+
nums의 길이 -> N
26+
시간 복잡도 : O(NlogN)
27+
공간 복잡도 : O(N)
28+
*/
29+
class Solution {
30+
public int[] list;
31+
public int lengthOfLIS(int[] nums) {
32+
int result = 0;
33+
list =new int[nums.length];
34+
Arrays.fill(list, Integer.MAX_VALUE);
35+
for(int i = 0; i < list.length; i++) {
36+
int idx = binarySearch(list, nums[i]);
37+
list[idx] = nums[i];
38+
result = Math.max(result, idx + 1);
39+
40+
}
41+
return result;
42+
}
43+
44+
public int binarySearch(int[] list, int target) {
45+
int start = 0;
46+
int end = list.length - 1;
47+
48+
while(start <= end) {
49+
int mid = (start + end) / 2;
50+
if(list[mid] >= target) {
51+
end = mid - 1;
52+
} else {
53+
start = mid + 1;
54+
}
55+
}
56+
57+
return start;
58+
}
59+
}

0 commit comments

Comments
 (0)