Skip to main content

23.js

/** ------------------------------------------------------------------------------
*
* 23. Merge k Sorted Lists
* Topics: Linked List
* https://leetcode.com/problems/merge-k-sorted-lists/description/
*
------------------------------------------------------------------------------ */
/**
* 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) {
if (!lists || !lists.length) return null

let arr = [],
res = new ListNode(0)

for (let i = 0; i < lists.length; i++) {
let cur = lists[i]
while (cur) {
arr.push(cur.val)
cur = cur.next
}
}
console.log(arr)

let cur = res

arr
.sort((a, b) => a - b)
.forEach((n) => {
let temp = new ListNode(n)
cur.next = temp
cur = cur.next
})
return res.next
}

console.log(
mergeKLists([
[1, 4, 5],
[1, 3, 4],
[2, 6],
]),
)