Skip to content

Commit 7d0ddc9

Browse files
committed
add solution : 300. Longest Increasing Subsequence
1 parent d08bcbe commit 7d0ddc9

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
*
3+
* @link https://leetcode.com/problems/longest-increasing-subsequence/description/
4+
*
5+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• : dp ์‚ฌ์šฉ
6+
* - dp[i]์— i๋ฒˆ์งธ ์š”์†Œ ํฌํ•จํ•œ LIS ๊ธธ์ด ์ €์žฅ
7+
* - ํ˜„์žฌ ๊ฐ’์ด ์ด์ „๊ฐ’๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ, ์ด์ „๊ฐ’ ์ˆœํšŒํ•˜๋ฉด์„œ LIS ์—…๋ฐ์ดํŠธํ•˜๊ธฐ
8+
*
9+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(n^2)
10+
* - ๊ฐ nums ์ˆœํšŒํ•˜๋ฉด์„œ ์ด์ „๊ฐ’ ๋น„๊ตํ•˜๊ธฐ ์œ„ํ•ด ์ˆœํšŒํ•˜๋‹ˆ๊นŒ O(n^2)
11+
*
12+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(n)
13+
* - nums ๊ธธ์ด๋งŒํผ dp ๋ฐฐ์—ด ์ƒ์„ฑํ•˜๋‹ˆ๊นŒ O(n)
14+
*/
15+
16+
function lengthOfLIS(nums: number[]): number {
17+
const dp = Array(nums.length).fill(1);
18+
19+
for (let i = 1; i < nums.length; i++) {
20+
for (let j = 0; j < i; j++) {
21+
if (nums[j] < nums[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
22+
}
23+
}
24+
25+
return Math.max(...dp);
26+
}
27+
28+
/**
29+
*
30+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• : ์ด์ง„ ํƒ์ƒ‰ ์‚ฌ์šฉ
31+
* - num ์‚ฝ์ž…ํ•  ์ธ๋ฑ์Šค ์ฐพ๊ธฐ ์œ„ํ•ด์„œ ์ด์ง„ ํƒ์ƒ‰ ์‚ฌ์šฉ
32+
* - nums ๋ฐฐ์—ด ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ num์˜ ์œ„์น˜ ์ฐพ๊ธฐ
33+
* - ์œ„์น˜๊ฐ€ ๋ฐฐ์—ด ๋‚ด์— ์กด์žฌํ•˜๋ฉด ๊ธฐ์กด ๊ฐ’์„ ๋Œ€์ฒดํ•˜๊ณ , ์œ„์น˜๊ฐ€ ๋ฐฐ์—ด ๊ธธ์ด๋ณด๋‹ค ํฌ๋ฉด ๋ฐฐ์—ด์— ์ถ”๊ฐ€
34+
*
35+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(nlogn)
36+
* - nums ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ์— ๋Œ€ํ•ด ์ด์ง„ ํƒ์ƒ‰ O(nlogn)
37+
*
38+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(n)
39+
* - arr์˜ ์ตœ๋Œ€ ํฌ๊ธฐ๊ฐ€ nums ๊ธธ์ด๋งŒํผ ํ•„์š”
40+
*/
41+
42+
function lengthOfLIS(nums: number[]): number {
43+
const arr: number[] = [];
44+
45+
nums.forEach((num) => {
46+
let left = 0,
47+
right = arr.length;
48+
// num ์‚ฝ์ž…ํ•  ์œ„์น˜๋ฅผ ์ด์ง„ ํƒ์ƒ‰์œผ๋กœ ์ฐพ์Œ
49+
while (left < right) {
50+
const mid = Math.floor((left + right) / 2);
51+
52+
if (arr[mid] < num) {
53+
left = mid + 1;
54+
} else right = mid;
55+
}
56+
57+
// ๊ธฐ์กด ๊ฐ’ ๋Œ€์ฒด
58+
if (left < arr.length) arr[left] = num;
59+
// ์ƒˆ๋กœ์šด ๊ฐ’ ์ถ”๊ฐ€
60+
else arr.push(num);
61+
});
62+
63+
return arr.length;
64+
}

0 commit comments

Comments
ย (0)