Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d9bca8a

Browse files
author
Shuo
authored
Merge pull request #780 from openset/develop
A: Merge k Sorted Lists
2 parents f2aeca3 + 4c914e9 commit d9bca8a

File tree

3 files changed

+84
-1
lines changed

3 files changed

+84
-1
lines changed

‎problems/merge-k-sorted-lists/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@
2626
</pre>
2727

2828
### Related Topics
29-
[[Heap](../../tag/heap/README.md)]
3029
[[Linked List](../../tag/linked-list/README.md)]
3130
[[Divide and Conquer](../../tag/divide-and-conquer/README.md)]
31+
[[Heap](../../tag/heap/README.md)]
3232

3333
### Similar Questions
3434
1. [Merge Two Sorted Lists](../merge-two-sorted-lists) (Easy)
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,34 @@
11
package problem23
2+
3+
import "github.com/openset/leetcode/internal/kit"
4+
5+
// ListNode - Definition for singly-linked list.
6+
type ListNode = kit.ListNode
7+
8+
/**
9+
* Definition for singly-linked list.
10+
* type ListNode struct {
11+
* Val int
12+
* Next *ListNode
13+
* }
14+
*/
15+
func mergeKLists(lists []*ListNode) *ListNode {
16+
var ans *ListNode
17+
for _, l := range lists {
18+
ans = mergeTwoLists(ans, l)
19+
}
20+
return ans
21+
}
22+
23+
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
24+
if l1 == nil {
25+
return l2
26+
} else if l2 == nil {
27+
return l1
28+
}
29+
if l1.Val > l2.Val {
30+
l1, l2 = l2, l1
31+
}
32+
l1.Next = mergeTwoLists(l1.Next, l2)
33+
return l1
34+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,51 @@
11
package problem23
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
7+
"github.com/openset/leetcode/internal/kit"
8+
)
9+
10+
type testType struct {
11+
in [][]int
12+
want []int
13+
}
14+
15+
func TestMergeKLists(t *testing.T) {
16+
tests := [...]testType{
17+
{
18+
in: [][]int{
19+
{1, 4, 5},
20+
{1, 3, 4},
21+
{2, 6},
22+
},
23+
want: []int{1, 1, 2, 3, 4, 4, 5, 6},
24+
},
25+
{
26+
in: [][]int{
27+
{2},
28+
{},
29+
{-1},
30+
},
31+
want: []int{-1, 2},
32+
},
33+
{
34+
in: [][]int{
35+
{},
36+
{},
37+
},
38+
want: nil,
39+
},
40+
}
41+
for _, tt := range tests {
42+
lists := make([]*ListNode, len(tt.in))
43+
for i, v := range tt.in {
44+
lists[i] = kit.SliceInt2ListNode(v)
45+
}
46+
got := kit.ListNode2SliceInt(mergeKLists(lists))
47+
if !reflect.DeepEqual(got, tt.want) {
48+
t.Fatalf("in: %v, got: %v, want: %v", tt.in, got, tt.want)
49+
}
50+
}
51+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /