[LeetCode#23] Merge K sorted Lists

2024. 8. 6. 19:21·Algorithm/문제풀이

❒ Description


제목 Merge K sorted Lists
링크 https://leetcode.com/problems/merge-k-sorted-lists/description/
자료구조 선형 (우선순위 큐)
시간복잡도 O(nlogk)

 

이번 문제에서도 가상의 노드 Root를 사용되었다. 이쯤 느껴지는 것은 뭔가 정렬이 들어가는

경우에는 가상의 노드 접근을 생각해보는 것도 좋은 거 같다.

 

아무튼 문제의 핵심은 자료구조 Priority Queue를 사용해서 해결하는 문제였다.

Priory Queue에 대한 정리는 이곳에 할 것이다. 

 

 

 

❒ Solution


전체 코드
더보기
public ListNode mergeKLists(ListNode[] lists) {
    PriorityQueue<ListNode> pq = new PriorityQueue<>((o1, o2) -> {
        if (o1.val == o2.val) {
            return 0;
        } else if (o1.val > o2.val) {
            return 1;
        } else {
            return -1;
        }
    });

    ListNode root = new ListNode(0);
    ListNode tail = root;

    for (ListNode node : lists) {
        if (node != null) {
            pq.add(node);
        }
    }
    while (!pq.isEmpty()) {
        ListNode poll = pq.poll();
        tail.next = poll;
        tail = tail.next;
        if (tail.next != null) {
            pq.add(poll.next);
        }
    }
    return root.next;
}

 

1. Priority Queue 인스턴스 생성 (with. Compator)

PriorityQueue<ListNode> pq = new PriorityQueue<>((o1, o2) -> {
    if (o1.val == o2.val) {
        return 0;
    } else if (o1.val > o2.val) {
        return 1;
    } else {
        return -1;
    }
});
  • `o1.val == o2.val` : 동일한 값이면 무시
  • `o1.val > o2.val` : 새로운 값(o1)이 기본 값(o2) 보다 크면 뒤에 위치
  • `그 외` : 작으면 앞에 위치

여기서는 Priority Queue 요소들의 크기를 비교하는 Comparator를 작성해준다.

이렇게 해줘야 Q에 새로운 요소를 삽입할 때 작은 값이 맨 앞에 위치하게 된다.

 

 

2. while loop

 

while (!pq.isEmpty()) {
    ListNode poll = pq.poll();
    tail.next = poll;
    tail = tail.next;
    if (tail.next != null) {
        pq.add(poll.next);
    }
}

 

문제에서 주어진 input 값은 `[ [1, 4, 5], [1 , 3, 4] ,[2 ,6] ]` 이다.

  • 1 → 4 → 5
  • 1 → 3 → 4
  • 2 → 6
pq tail
[1, 1, 2] 1
[1, 2, 4] 1 -> 1
[2, 4, 3] 1 -> 1 -> 2
[3, 4, 6] 1 -> 1 -> 2 ->  3
[4, 6, 4] 1 -> 1 -> 2 -> 3 -> 4
[4, 6, 5] 1 -> 1 -> 2 -> 3 -> 4 -> 4
[5, 6] 1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5
[6] 1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6

 

'Algorithm > 문제풀이' 카테고리의 다른 글

[프로그래머스#42576] 완주하지 못한 선수  (0) 2024.08.16
[LeetCode#973] K Closest Points to Origin  (0) 2024.08.08
[LeetCode#641] Design Circular Deque  (0) 2024.08.05
[LeetCode#622] Design Circular Queue  (0) 2024.08.04
[LeetCode#739] Daily Temperatures  (0) 2024.07.31
'Algorithm/문제풀이' 카테고리의 다른 글
  • [프로그래머스#42576] 완주하지 못한 선수
  • [LeetCode#973] K Closest Points to Origin
  • [LeetCode#641] Design Circular Deque
  • [LeetCode#622] Design Circular Queue
gilbert9172
gilbert9172
gilbert9172 님의 블로그 입니다.
  • gilbert9172
    バックエンド
    gilbert9172
  • 전체
    오늘
    어제
    • All Categories (166)
      • 우테코 7기 (21)
        • 1주차 (8)
        • 2주차 (5)
        • 3주차 (6)
      • Langauge (4)
        • Java (3)
        • Kotlin (1)
      • Back-End (13)
        • SpringBoot (1)
        • Trouble Shooting (0)
        • Setup & Configuration (1)
        • SQL (3)
        • Redis (8)
      • Architecture (6)
        • Multi Module (1)
        • DDD (5)
      • CS (30)
        • Data Structure (6)
        • Operating System (0)
        • Network (12)
        • Database (10)
        • Design Pattern (2)
      • Algorithm (78)
        • 내용 정리 (18)
        • 문제풀이 (60)
      • DevOps (6)
        • AWS (5)
        • Git (1)
      • Front-End (1)
        • Trouble Shooting (1)
      • Project (6)
        • 페이스콕 (6)
      • Book (0)
        • 마스터링 블록체인 (0)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    Two-Pointer
    sliding-window
    Back-Tracking
    greedy
    binarysearch
    오블완
    부분단조성
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
gilbert9172
[LeetCode#23] Merge K sorted Lists
상단으로

티스토리툴바