228. Summary Ranges
2026/1/12大约 2 分钟约 494 字
228. Summary Ranges
难度: Easy
题目描述
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"ifa != b"a"ifa == b
Example 1:
Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: The ranges are: [0,2] --> "0->2" [4,5] --> "4->5" [7,7] --> "7"
Example 2:
Input: nums = [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] Explanation: The ranges are: [0,0] --> "0" [2,4] --> "2->4" [6,6] --> "6" [8,9] --> "8->9"
Constraints:
0 <= nums.length <= 20-231 <= nums[i] <= 231 - 1- All the values of
numsare unique. numsis sorted in ascending order.
解题思路
代码实现
解决方案
java
func summaryRanges(nums []int) []string {
result := make([][]int, 0)
for i := 0; i < len(nums); {
newIndex, temp := find(nums, i)
result = append(result, temp)
i = newIndex + 1
}
data := []string{}
for _, d := range result {
if d[1] == d[0] {
data = append(data, strconv.Itoa(d[0]))
} else {
data = append(data, strconv.Itoa(d[0])+"->"+strconv.Itoa(d[1]))
}
}
return data
}
func find(nums []int, s int) (int, []int) {
var result = []int{}
result = append(result, nums[s])
result = append(result, nums[s])
for i := s + 1; i < len(nums); i++ {
if nums[i]-nums[i-1] != 1 {
result[1] = nums[i-1]
return i - 1, result
}
if i == len(nums)-1 {
result[1] = nums[i]
return i, result
}
}
return s, result
}