File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments