[Leetcode] 23. Merge k Sorted Lists โ
Problem โ
๋ฐฐ์ด์ ์ฃผ์ด์ง k
๊ฐ์ linked list
๋ฅผ ๋ชจ๋ ๋จธ์งํ๋ ๋ฌธ์
Solution โ
Merge Two Sorted Lists ๋ฌธ์ ์ ํ์ด๋ฐฉ๋ฒ์ ๊ฐ์
- ๋ชจ๋ ๋ ธ๋๊ฐ ๊ฐ์ ์์๋๊น์ง ๋ฐ๋ณต๋ฌธ์ ์คํ
- ๊ฐ์ฅ ์์ ๊ฐ์ ๊ฐ์ง ๋ ธ๋๋ฅผ ์ฐพ์.
- ํด๋น ๋
ธ๋๋ฅผ ์ด๋ํ๊ณ ๊ฐ์ง๊ณ ์๋ ๊ฐ์ ์ด์ฉํด ์๋ก์ด ๋
ธ๋๋ฅผ ์์ฑํ๊ณ
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
};