배열에 주어진 k
개의 linked list
를 모두 머지하는 문제
Merge Two Sorted Lists 문제와 풀이방법은 같음
head
에 이어붙임./**
* 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
};