Skip to content

Commit 69660f2

Browse files
authored
merge k sorted lists solution
1 parent 24f627d commit 69660f2

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

merge-k-sorted-lists/yhkee0404.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* type ListNode struct {
4+
* Val int
5+
* Next *ListNode
6+
* }
7+
*/
8+
9+
type Heap []*ListNode
10+
11+
func (pq Heap) Len() int {return len(pq)}
12+
func (pq Heap) Less(i, j int) bool {
13+
return pq[i].Val < pq[j].Val
14+
}
15+
func (pq Heap) Swap(i, j int) {pq[i], pq[j] = pq[j], pq[i]}
16+
func (pq *Heap) Push(x any) {*pq = append(*pq, x.(*ListNode))}
17+
func (pq *Heap) Pop() any {
18+
x := (*pq)[len(*pq) - 1]
19+
*pq = (*pq)[:len(*pq) - 1]
20+
return x
21+
}
22+
23+
func mergeKLists(lists []*ListNode) *ListNode {
24+
h := Heap{}
25+
for _, l := range lists {
26+
if l != nil {
27+
h = append(h, l)
28+
}
29+
}
30+
heap.Init(&h)
31+
ans := ListNode{}
32+
u := &ans
33+
for len(h) > 0 { // T(n) = S(n) = O(nlogn)
34+
u.Next = heap.Pop(&h).(*ListNode)
35+
u = u.Next
36+
if u.Next != nil {
37+
heap.Push(&h, u.Next)
38+
}
39+
}
40+
return ans.Next
41+
}

0 commit comments

Comments
 (0)