題目
You are given a sorted unique integer array nums.
A range [a,b] is the set of all integers from a to b (inclusive).
Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.
Each range [a,b] in the list should be output as:
“a->b” if a != b “a” if a == b
解法
- 透過不連續數字,我們可以找出連續數字並且輸出一個range,若是range數字是一樣的則輸出數字,若不一樣則輸出range
import (
"strconv"
)
func summaryRanges(nums []int) []string {
if len(nums) == 1 {
return []string{strconv.Itoa(nums[0])}
}
var res []string
start := 0
for i := 1; i < len(nums); i++ {
if nums[i]-nums[i-1] != 1 {
res = append(res, buildResString(nums[start], nums[i-1]))
start = i
}
if len(nums)-1 == i {
res = append(res, buildResString(nums[start], nums[i]))
}
}
return res
}
func buildResString(i1, i2 int) string {
if i1 == i2 {
return strconv.Itoa(i1)
}
return strconv.Itoa(i1) + "->" + strconv.Itoa(i2)
}
- 加些測試,看看結果是不是如預期
func Test_summaryRanges(t *testing.T) {
assert.Equal(t, []string{"0->2", "4->5", "7"}, summaryRanges([]int{0, 1, 2, 4, 5, 7}))
assert.Equal(t, []string{"0", "2->4", "6", "8->9"}, summaryRanges([]int{0, 2, 3, 4, 6, 8, 9}))
assert.Equal(t, []string{"-1"}, summaryRanges([]int{-1}))
}