Skip to content

Commit 24caa06

Browse files
aQuaaQua
aQua
authored and
aQua
committed
88 accepted
1 parent fbb0ab6 commit 24caa06

File tree

3 files changed

+67
-11
lines changed

3 files changed

+67
-11
lines changed
Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
# [88. Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)
22

33
## 题目
4+
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
45

6+
Note:
57

6-
## 解题思路
7-
8-
9-
## 总结
8+
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
109

10+
## 解题思路
11+
见程序注释
1112

13+
## 总结
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,32 @@
11
package Problem0088
22

3+
// 本题的要求是,把nums1的前m项和nums2的前n项合并,放入nums1中。
4+
func merge(nums1 []int, m int, nums2 []int, n int) {
5+
// 深度复制 nums1
6+
temp := make([]int, m)
7+
copy(temp, nums1)
8+
9+
j, k := 0, 0
10+
for i := 0; i < len(nums1); i++ {
11+
// nums2用完了
12+
if k >= n {
13+
nums1[i] = temp[j]
14+
j++
15+
continue
16+
}
17+
// temp 用完了
18+
if j >= m {
19+
nums1[i] = nums2[k]
20+
k++
21+
continue
22+
}
23+
// 比较后,放入
24+
if temp[j] < nums2[k] {
25+
nums1[i] = temp[j]
26+
j++
27+
} else {
28+
nums1[i] = nums2[k]
29+
k++
30+
}
31+
}
32+
}
Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package Problem0088
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
66

77
"github.com/stretchr/testify/assert"
88
)
@@ -15,13 +15,16 @@ type question struct {
1515
// para 是参数
1616
// one 代表第一个参数
1717
type para struct {
18-
one string
18+
one []int
19+
m int
20+
two []int
21+
n int
1922
}
2023

2124
// ans 是答案
2225
// one 代表第一个答案
2326
type ans struct {
24-
one string
27+
one []int
2528
}
2629

2730
func Test_Problem0088(t *testing.T) {
@@ -30,17 +33,38 @@ func Test_Problem0088(t *testing.T) {
3033
qs := []question{
3134

3235
question{
33-
para{""},
34-
ans{""},
36+
para{[]int{0}, 0, []int{1}, 1},
37+
ans{[]int{1}},
38+
},
39+
40+
question{
41+
para{[]int{1, 0}, 1, []int{2}, 1},
42+
ans{[]int{1, 2}},
43+
},
44+
45+
question{
46+
para{[]int{}, 0, []int{1}, 1},
47+
ans{[]int{}},
3548
},
36-
49+
50+
question{
51+
para{[]int{1, 3, 5, 7}, 4, []int{2, 4}, 2},
52+
ans{[]int{1, 2, 3, 4}},
53+
},
54+
55+
question{
56+
para{[]int{1, 3, 5, 7}, 4, []int{2, 2}, 2},
57+
ans{[]int{1, 2, 2, 3}},
58+
},
59+
3760
// 如需多个测试,可以复制上方元素。
3861
}
3962

4063
for _, q := range qs {
4164
a, p := q.ans, q.para
4265
fmt.Printf("~~%v~~\n", p)
4366

44-
ast.Equal(a.one, (p.one), "输入:%v", p)
67+
merge(p.one, p.m, p.two, p.n)
68+
ast.Equal(a.one, p.one, "输入:%v", p)
4569
}
4670
}

0 commit comments

Comments
 (0)