Skip to content

[Leetcode] 23. Merge k Sorted Lists โ€‹

Problem โ€‹

๋ฌธ์ œ ๋งํฌ

๋ฐฐ์—ด์— ์ฃผ์–ด์ง„ k๊ฐœ์˜ linked list๋ฅผ ๋ชจ๋‘ ๋จธ์ง€ํ•˜๋Š” ๋ฌธ์ œ

Solution โ€‹

Merge Two Sorted Lists ๋ฌธ์ œ์™€ ํ’€์ด๋ฐฉ๋ฒ•์€ ๊ฐ™์Œ

  1. ๋ชจ๋“  ๋…ธ๋“œ๊ฐ€ ๊ฐ’์„ ์žƒ์„๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต๋ฌธ์„ ์‹คํ–‰
  2. ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ๊ฐ€์ง„ ๋…ธ๋“œ๋ฅผ ์ฐพ์Œ.
  3. ํ•ด๋‹น ๋…ธ๋“œ๋ฅผ ์ด๋™ํ•˜๊ณ  ๊ฐ€์ง€๊ณ ์žˆ๋˜ ๊ฐ’์„ ์ด์šฉํ•ด ์ƒˆ๋กœ์šด ๋…ธ๋“œ๋ฅผ ์ƒ์„ฑํ•˜๊ณ  head์— ์ด์–ด๋ถ™์ž„.

JS Code โ€‹

javascript
/**
 * 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}
 */
var mergeKLists = function(lists) {
    const head = new ListNode()
    let rear = head
    
    const getNodeVal = (lists, idx) => {
        const { val, next } = lists[idx]
        lists[idx] = next
        return val
    }
    
    while(lists.some(node => node)) {
        const minVal = lists.reduce((acc,cur) => (acc?.val ?? Number.MAX_SAFE_INTEGER) < (cur?.val ?? Number.MAX_SAFE_INTEGER) ? acc : cur).val
        const minValNodeIdx = lists.findIndex(node => node && node.val === minVal)
        const newNode = new ListNode(getNodeVal(lists, minValNodeIdx))
        if (!head.next) head.next = newNode
        else rear.next = newNode
        
        rear = rear.next
    }
    
    return head.next
};