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 : lists = [[1,4,5],[1,3,4],[2,6]] Output : [1,1,2,3,4,4,5,6]

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

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

Constraints :

  • k == lists.length

  • 0 <= k <= 10^4

  • 0 <= lists[i].length <= 500

  • -10^4 <= lists[i][j] <= 10^4

  • lists[i] is sorted in ascending order.

  • The sum of lists[i].length won't exceed 10^4.

์ž๋ฃŒ๊ตฌ์กฐ : ์šฐ์„ ์ˆœ์œ„ ํ(=์ •๋ ฌ), ๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ ์ด์šฉ

์•Œ๊ณ ๋ฆฌ์ฆ˜ 1. ์ž๋ฃŒ๊ตฌ์กฐ ์ƒ์„ฑ 2. ์šฐ์„ ์ˆœ์œ„ ํ(์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ)์— ๋ฐ์ดํ„ฐ ๋„ฃ๋Š”๋‹ค. 3. ํ์—์„œ ๋ฐ์ดํ„ฐ ๋นผ๋ฉด์„œ ์ •๋‹ต๋ฆฌ์ŠคํŠธ์— ๋„ฃ๋Š”๋‹ค.//+ํ์—์„œ ๋นผ๋ ค๋Š” ๋ฐ์ดํ„ฐ์˜ ๋‹ค์Œ ๋…ธ๋“œ๊ฐ€ Null์ด ์•„๋‹ˆ๋ฉด node.next๋ฅผ ํ์— ๋„ฃ๋Š”๋‹ค.

์•Œ๊ณ ๋ฆฌ์ฆ˜์„ Java๋กœ ๊ตฌํ˜„

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        //1.์ž๋ฃŒ๊ตฌ์กฐ ์ƒ์„ฑ
        ListNode dummyHead = new ListNode(0);
        ListNode p = dummyHead;
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(Comp);
        
        //2.ํ์— ๋ฐ์ดํ„ฐ ๋‹ด๊ธฐ
        for(ListNode node : lists) {
            if(node != null) {
                queue.offer(node);
            }
        }
        //3.ํ์—์„œ ๋ฐ์ดํ„ฐ ๋นผ๋ฉด์„œ ์ •๋‹ต ๋ฆฌ์ŠคํŠธ์— ๋‹ด๊ธฐ
        while(!queue.isEmpty()) {//๋น„์ง€ ์•Š๋Š” ๋™์•ˆ๋งŒ(๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ์„ ๋•Œ๋งŒ).
            ListNode node = queue.poll();
            p.next = node;
            p = p.next;
            if(node.next != null) {
                queue.offer(node);
            }
        }
        return dummyHead.next;
    }
    Comparator<ListNode> Comp = new Comparator<ListNode>(){
        public int compare(ListNode l1, ListNode l2) {
            return l1.val - l2.val;//ascending order
        }
    };
}

Last updated