Skip to content

Commit

Permalink
add solution : 23. Merge k Sorted Lists
Browse files Browse the repository at this point in the history
  • Loading branch information
mmyeon committed Feb 15, 2025
1 parent 4d28d87 commit e9d57a6
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions merge-k-sorted-lists/mmyeon.ts
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;
}

0 comments on commit e9d57a6

Please sign in to comment.