Skip to content

Commit

Permalink
feat: Upload merge-k-sorted-lists (typescript)
Browse files Browse the repository at this point in the history
  • Loading branch information
mike2ox committed Feb 15, 2025
1 parent 1744c14 commit fb9e520
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions merge-k-sorted-lists/mike2ox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Source: https://leetcode.com/problems/merge-k-sorted-lists/
* 풀이방법: 모든 리스트들을 한곳에 넣고 재배치
*
* 시간복잡도: O(NlogN) - 모든 리스트를 순회(N), 정렬(NlogN) 하는데 드는 시간 고려
* 공간복잡도: O(N) - 기존 배열을 저장할 공간만 필요
*/

/**
* Definition for singly-linked list.
* 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)
* }
* }
*/

function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
if (!lists?.length) return null;
let merged = [];

for (let i = 0; i < lists.length; i++) {
let cursor = lists[i];
while (cursor != null) {
merged.push(cursor.val);
cursor = cursor.next;
}
}
let sorted = merged.sort((a, b) => (a < b ? -1 : 1));
let head = null;
let tail = null;

for (let i = 0; i < sorted.length; i++) {
const node = new ListNode(sorted[i], null);
if (head === null) {
head = node;
tail = node;
} else {
tail.next = node;
tail = node;
}
}

return head;
}

0 comments on commit fb9e520

Please sign in to comment.