leetcode 228. 汇总区间

题解

首先初始化startend代表区间的首尾,然后遍历nums找出连续的数字

示例代码(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
func summaryRanges(nums []int) []string {
res := make([]string, 0)
if len(nums) == 0 {
return res
}
start, end := nums[0], nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] == nums[i-1]+1 {
end = nums[i]
continue
}
res = append(res, sprintf(start, end))
start = nums[i]
end = nums[i]
}
res = append(res, sprintf(start, end))
return res
}

func sprintf(start int, end int) string {
str := ""
if start != end {
str = fmt.Sprintf("%d->%d", start, end)
} else {
str = fmt.Sprintf("%d", start)
}
return str
}