-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add solution : 23. Merge k Sorted Lists
- Loading branch information
Showing
1 changed file
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
class ListNode { | ||
val: number; | ||
next: ListNode | null; | ||
constructor(val?: number, next?: ListNode | null) { | ||
this.val = val === undefined ? 0 : val; | ||
this.next = next === undefined ? null : next; | ||
} | ||
} | ||
|
||
/** | ||
* @link https://leetcode.com/problems/merge-k-sorted-lists/description/ | ||
* | ||
* ์ ๊ทผ ๋ฐฉ๋ฒ : | ||
* - ๋ฆฌ์คํธ๋ฅผ ๋ฐฐ์ด์ ๋ฃ๊ณ , ์ต์๊ฐ์ ๊ฐ์ง ๋ ธ๋ ์ฐพ๊ธฐ | ||
* - ์ต์๊ฐ ๋ ธ๋๋ฅผ ๋๋ฏธ ๋ ธ๋์ ์ฐ๊ฒฐํ ๋ค ์ ๊ฑฐํ๊ณ , ์ต์๊ฐ ๋ ธ๋์ ๋ค์ ๋ ธ๋๋ฅผ ๋ค์ ๋ฐฐ์ด์ ์ถ๊ฐํ๊ธฐ | ||
* - ๋ฐฐ์ด ๊ธธ์ด๊ฐ 0์ด ๋ ๋๊น์ง ๋ฐ๋ณตํ๊ธฐ | ||
* | ||
* ์๊ฐ๋ณต์ก๋ : O(n * k) | ||
* - n = ์ด ๋ ธ๋์ ๊ฐ์ | ||
* - k = ๋ฆฌ์คํธ์ ๊ฐ์ | ||
* - ์ต์๊ฐ ์ฐพ๊ณ , ์ต์๊ฐ ์ ๊ฑฐํ๋ ๋ก์ง: O(k) | ||
* - ์์ ์ฐ์ฐ์ ์ด n๋ฒ ์คํ | ||
* | ||
* ๊ณต๊ฐ๋ณต์ก๋ : O(k) | ||
* - k = ๋ฆฌ์คํธ ๊ฐ์ | ||
* - minList ๋ฐฐ์ด์ ํฌ๊ธฐ๊ฐ ์ต๋ K๊ฐ๊น์ง ์ ์ง | ||
* | ||
*/ | ||
|
||
function mergeKLists(lists: Array<ListNode | null>): ListNode | null { | ||
const minList: ListNode[] = []; | ||
|
||
for (const list of lists) { | ||
if (list !== null) minList.push(list); | ||
} | ||
|
||
const dummy = new ListNode(); | ||
let tail = dummy; | ||
|
||
while (minList.length > 0) { | ||
const minIndex = getMinIndex(minList); | ||
const minNode = minList.splice(minIndex, 1)[0]; | ||
|
||
tail.next = minNode; | ||
tail = tail.next; | ||
|
||
if (minNode.next) minList.push(minNode.next); | ||
} | ||
|
||
return dummy.next; | ||
} | ||
|
||
function getMinIndex(nodes: ListNode[]): number { | ||
let minIndex = 0; | ||
|
||
for (let i = 1; i < nodes.length; i++) { | ||
if (nodes[i].val < nodes[minIndex].val) minIndex = i; | ||
} | ||
|
||
return minIndex; | ||
} |