Skip to content

A: Merge k Sorted Lists #780

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion problems/merge-k-sorted-lists/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@
</pre>

### Related Topics
[[Heap](../../tag/heap/README.md)]
[[Linked List](../../tag/linked-list/README.md)]
[[Divide and Conquer](../../tag/divide-and-conquer/README.md)]
[[Heap](../../tag/heap/README.md)]

### Similar Questions
1. [Merge Two Sorted Lists](../merge-two-sorted-lists) (Easy)
Expand Down
33 changes: 33 additions & 0 deletions problems/merge-k-sorted-lists/merge_k_sorted_lists.go
Original file line number Diff line number Diff line change
@@ -1 +1,34 @@
package problem23

import "github.com/openset/leetcode/internal/kit"

// ListNode - Definition for singly-linked list.
type ListNode = kit.ListNode

/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeKLists(lists []*ListNode) *ListNode {
var ans *ListNode
for _, l := range lists {
ans = mergeTwoLists(ans, l)
}
return ans
}

func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
} else if l2 == nil {
return l1
}
if l1.Val > l2.Val {
l1, l2 = l2, l1
}
l1.Next = mergeTwoLists(l1.Next, l2)
return l1
}
50 changes: 50 additions & 0 deletions problems/merge-k-sorted-lists/merge_k_sorted_lists_test.go
Original file line number Diff line number Diff line change
@@ -1 +1,51 @@
package problem23

import (
"reflect"
"testing"

"github.com/openset/leetcode/internal/kit"
)

type testType struct {
in [][]int
want []int
}

func TestMergeKLists(t *testing.T) {
tests := [...]testType{
{
in: [][]int{
{1, 4, 5},
{1, 3, 4},
{2, 6},
},
want: []int{1, 1, 2, 3, 4, 4, 5, 6},
},
{
in: [][]int{
{2},
{},
{-1},
},
want: []int{-1, 2},
},
{
in: [][]int{
{},
{},
},
want: nil,
},
}
for _, tt := range tests {
lists := make([]*ListNode, len(tt.in))
for i, v := range tt.in {
lists[i] = kit.SliceInt2ListNode(v)
}
got := kit.ListNode2SliceInt(mergeKLists(lists))
if !reflect.DeepEqual(got, tt.want) {
t.Fatalf("in: %v, got: %v, want: %v", tt.in, got, tt.want)
}
}
}