Skip to content

Commit 4fe9190

Browse files
aQuaaQua
aQua
authored and
aQua
committed
228 UT pass
1 parent 0c5bb9f commit 4fe9190

File tree

3 files changed

+113
-0
lines changed

3 files changed

+113
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# [228. Summary Ranges](https://leetcode.com/problems/summary-ranges/)
2+
3+
## 题目
4+
Given a sorted integer array without duplicates, return the summary of its ranges.
5+
6+
Example 1:
7+
```
8+
Input: [0,1,2,4,5,7]
9+
Output: ["0->2","4->5","7"]
10+
```
11+
12+
Example 2:
13+
```
14+
Input: [0,2,3,4,6,8,9]
15+
Output: ["0","2->4","6","8->9"]
16+
```
17+
18+
19+
## 解题思路
20+
21+
见程序注释
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package Problem0228
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func summaryRanges(a []int) []string {
8+
res := []string{}
9+
10+
l := len(a)
11+
if l == 0 {
12+
return res
13+
}
14+
15+
begin := a[0]
16+
str := ""
17+
for i := 1; i < l; i++ {
18+
if a[i-1]+1 != a[i] {
19+
if a[i-1] == begin {
20+
str = fmt.Sprintf("%d", begin)
21+
} else {
22+
str = fmt.Sprintf("%d->%d", begin, a[i-1])
23+
}
24+
begin = a[i]
25+
res = append(res, str)
26+
}
27+
}
28+
if a[l-1] == begin {
29+
str = fmt.Sprintf("%d", begin)
30+
} else {
31+
str = fmt.Sprintf("%d->%d", begin, a[l-1])
32+
}
33+
res = append(res, str)
34+
35+
return res
36+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package Problem0228
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type question struct {
11+
para
12+
ans
13+
}
14+
15+
// para 是参数
16+
type para struct {
17+
nums []int
18+
}
19+
20+
// ans 是答案
21+
type ans struct {
22+
one []string
23+
}
24+
25+
func Test_Problem0228(t *testing.T) {
26+
ast := assert.New(t)
27+
28+
qs := []question{
29+
30+
question{
31+
para{
32+
[]int{0, 1, 2, 4, 5, 7},
33+
},
34+
ans{
35+
[]string{"0->2", "4->5", "7"},
36+
},
37+
},
38+
39+
question{
40+
para{
41+
[]int{0, 2, 3, 4, 6, 8, 9},
42+
},
43+
ans{
44+
[]string{"0", "2->4", "6", "8->9"},
45+
},
46+
},
47+
// 如需多个测试,可以复制上方元素。
48+
}
49+
50+
for _, q := range qs {
51+
a, p := q.ans, q.para
52+
fmt.Printf("~~%v~~\n", p)
53+
54+
ast.Equal(a.one, summaryRanges(p.nums), "输入:%v", p)
55+
}
56+
}

0 commit comments

Comments
 (0)