题目
Given a sorted integer array without duplicates, return the summary of its ranges.
样例
For example, given [0,1,2,4,5,7], return [“0->2”,”4->5”,”7”]
解答
采用遍历的方法,如果后一个数不等于前一个数字加上+1 就证明后面的数字和前面的数字不在一个范围内。采用两个指针,分别记录一个范围的开始和结束。
vector<string> summaryRanges(vector<int>& nums) {
if (nums.empty())
return vector<string>();
vector<int>::size_type index;
vector<string> sv;
string begin = to_string(nums[0]);
string end;
string res;
for (index = 1; index < nums.size(); index++) {
end = to_string(nums[index - 1]);
if (nums[index] != nums[index - 1] + 1) {
if (begin != end)
res = begin + "->" + end;
else
res = begin;
begin = to_string(nums[index]);
sv.push_back(res);
}
}
if (begin > end)
sv.push_back(begin);
else
sv.push_back(begin + "->" + to_string(nums[nums.size() - 1]));
return sv;
}