Notice
Recent Posts
Recent Comments
Link
«   2026/01   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

eumjo_o

leetcode0023 - Merge k Sorted Lists / Hard / Typescript 본문

카테고리 없음

leetcode0023 - Merge k Sorted Lists / Hard / Typescript

eumjo_o 2023. 4. 30. 23:31

https://leetcode.com/problems/merge-k-sorted-lists/

 

Merge k Sorted Lists - LeetCode

Can you solve this real interview question? Merge k Sorted Lists - You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.   Example 1: Input: lis

leetcode.com

Time Complexity O(N log(N))

  • N은 node의 총 개수
    • 모든 value 들을 array에 담는 데 O(N)
    • value들을 정렬할 때, O(N log(N))
    • linked list를 다시 만들 때, O(N)의 시간

Space Complexity O(N)

  • value들을 정렬하기 위해서 만든 array가 O(N)
  • linked list를 만드는 데 사용되는 공간이 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 {
    const ansValues = [];

    for(let i = 0; i < lists.length; i++) {
        let node = lists[i];
        while(node) {
            ansValues.push(node.val);
            node = node.next;
        }
    }
    ansValues.sort((a,b) => a-b);

    const ansNodes = new ListNode(0);
    let tail = ansNodes;

    for(let j = 0; j < ansValues.length; j++) {
        tail.next = new ListNode(ansValues[j]);
        tail = tail.next;
    }

    return ansNodes.next;
};