[PS] Leet | 23. 정렬된 K개의 리스트 합치기

2025. 5. 9. 21:35·CS/PS

문제

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: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6


Example 2:
Input: lists = []
Output: []


Example 3:
Input: lists = [[]]
Output: []

조건

  • k == lists.length
  • 0 <= k <= 104
  • 0 <= lists[i].length <= 500
  • -104 <= lists[i][j] <= 104
  • lists[i] is sorted in ascending order.
  • The sum of lists[i].length will not exceed 104.

답

여러 개의 리스트 중에서 두 개 씩 선택해 합치는 분할 정복을 사용합니다.

 

위 과정을 계속 반복하면 lists에는 하나의 리스트만 남게 되고, 그것이 최종 결과물이 됩니다.

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
const mergeTwoLists = (list1, list2) => {
    let node = new ListNode(0, null);
    const head = node;

    while(list1 && list2) {
        if (list1?.val <= list2?.val) {
            node.next = list1;
            node = node.next;
            list1 = list1?.next;
        } else {
            node.next = list2;
            node = node.next;
            list2 = list2?.next;
        }
    }

    if (!list1) node.next = list2;
    if (!list2) node.next = list1;
    return head.next;
};

var mergeKLists = function(lists) {
    if (lists.length == 0) return null;

    while (lists.length > 1) {
        const listsMerged = [];

        for (let i=0; i<lists.length; i+=2) {
            const l1 = lists[i];
            const l2 = i+1 < lists.length? lists[i+1] : null;
            listsMerged.push(mergeTwoLists(l1, l2));
        }
        lists = listsMerged;
    }

    return lists[0];
};

총 node의 개수 N, 리스트의 개수 K일 때

 

시간 복잡도 : O(NlogK)

공간 복잡도 : O(1)

728x90

'CS > PS' 카테고리의 다른 글

[PS] Leet | 48. 이미지 회전  (0) 2025.05.21
[PS] Leet | 143. 리스트 재배치  (0) 2025.05.12
[PS] Leet | 141. 연결 리스트 순환  (0) 2025.05.03
[PS] Leet | 435. 겹치지 않는 구간들  (0) 2025.04.30
[PS] Leet | 57. 구간 삽입  (0) 2025.04.26
'CS/PS' 카테고리의 다른 글
  • [PS] Leet | 48. 이미지 회전
  • [PS] Leet | 143. 리스트 재배치
  • [PS] Leet | 141. 연결 리스트 순환
  • [PS] Leet | 435. 겹치지 않는 구간들
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (262) N
      • CS (40)
        • ML (3)
        • CV (2)
        • PS (34)
      • Reveiw (17)
        • Paper (17)
        • Github (0)
      • Pytorch (5)
      • Language (58)
        • Python (7)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (71) N
        • React (8)
        • SolidJS (20)
        • CSS (12) N
      • UI (3)
      • Backend (15)
        • DB (17)
        • Node.js (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    DB
    API
    figma
    ML
    Three
    Express
    ps
    react
    CV
    deploy
    html
    mongo
    vscode
    review
    python
    frontend
    js
    CS
    CSS
    ts
    PRISMA
    UI
    GAN
    PyTorch
    nodejs
    Git
    postgresql
    C++
    backend
    SOLID
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[PS] Leet | 23. 정렬된 K개의 리스트 합치기
상단으로

티스토리툴바