228. Summary Ranges
题目大意
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
中文释义
给你一个排序好的且不重复的整数数组 nums
。
一个范围 [a,b]
是从 a
到 b
的所有整数的集合(包括 a
和 b
)。
返回一个最小的排序范围列表,该列表完全覆盖数组中的所有数字。也就是说,nums
的每个元素都恰好被列表中的一个范围所覆盖,且不存在一个整数 x
被范围包含但不在 nums
中。
列表中的每个范围 [a,b]
应该按照以下格式输出:
- 如果
a != b
,输出"a->b"
- 如果
a == b
,输出"a"
示例
Example 1:
Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 范围为:
[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: 范围为:
[0,0] --> “0”
[2,4] --> “2->4”
[6,6] --> “6”
[8,9] --> “8->9”
限制条件
0 <= nums.length <= 20
-2^31 <= nums[i] <= 2^31 - 1
nums
中的所有值都是唯一的。nums
按升序排序。
解题思路
方法
即从给定的排序数组 nums
中找出并返回表示连续区间的字符串列表。
方法使用了双指针技术。
-
初始化:
- 创建一个空的字符串数组
ans
用于存储结果。
- 创建一个空的字符串数组
-
使用双指针遍历数组:
- 使用两个指针
start
和end
,其中start
指示当前连续区间的开始,而end
用于探索区间的结束。 - 遍历数组,对于每个位置
end
:- 检查当前位置是否是连续区间的结束,这通过比较
nums[end]
和nums[end + 1]
来判断。如果end + 1
是数组的末尾,或者nums[end + 1]
和nums[end]
不连续,则当前区间结束。 - 根据区间的起始和结束位置,构造区间字符串。如果
start
和end
相同,表示区间只包含一个元素,直接使用nums[start]
的值。如果不同,则构造一个 “start->end” 的字符串。 - 将构造的区间字符串添加到结果数组
ans
中。 - 更新
start
为下一个可能区间的起点。
- 检查当前位置是否是连续区间的结束,这通过比较
- 使用两个指针
-
返回结果:
- 完成遍历后,返回包含所有连续区间的字符串数组
ans
。
- 完成遍历后,返回包含所有连续区间的字符串数组
代码
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ans;
for (int start = 0, end = 0; end < nums.size(); end++) {
if (end + 1 == nums.size() || (long)nums[end + 1] - nums[end] != 1) {
if (start == end) {
ans.push_back(to_string(nums[start]));
} else {
ans.push_back(to_string(nums[start]) + "->" + to_string(nums[end]));
}
start = end + 1;
}
}
return ans;
}
};