-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path228.汇总区间.go
55 lines (45 loc) · 1.02 KB
/
228.汇总区间.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"fmt"
)
func main() {
var nums []int
nums = []int{0, 1, 2, 4, 5, 7}
fmt.Printf("%#v\n", summaryRanges(nums))
nums = []int{0, 2, 3, 4, 6, 8, 9}
fmt.Printf("%#v\n", summaryRanges(nums))
nums = []int{}
fmt.Printf("%#v\n", summaryRanges(nums))
nums = []int{-1}
fmt.Printf("%#v\n", summaryRanges(nums))
nums = []int{0}
fmt.Printf("%#v\n", summaryRanges(nums))
}
func summaryRanges(nums []int) []string {
if len(nums) == 0 {
return []string{}
}
res := [][]int{}
for i := 0; i < len(nums); i++ {
if i == 0 {
res = append(res, []int{nums[i]})
} else if nums[i] == nums[i-1]+1 {
lastIndex := len(res) - 1
res[lastIndex] = append(res[lastIndex], nums[i])
} else {
res = append(res, []int{nums[i]})
}
}
var res2 []string
var tmp string
for i := 0; i < len(res); i++ {
if len(res[i]) == 1 {
tmp = fmt.Sprintf("%d", res[i][0])
res2 = append(res2, tmp)
} else {
tmp = fmt.Sprintf("%d->%d", res[i][0], res[i][len(res[i])-1])
res2 = append(res2, tmp)
}
}
return res2
}