题目
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”].
翻译
假设有一个已排序整数数组,不包含重复的元素,返回其范围摘要
思路
开始定义一个范围的起始地址。
遍历数组,如果连续,则继续遍历,如果不连续,则出现一段,得到范围结束地址,保存结果即可。
更新起始地址,接着遍历
代码
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
int start = 0; //最小值
int end = nums.size(); //最大值
if(end == 0){
return res;
}
int t_s = nums[0]; //初始值
int t_e = nums[0]; //终点值
int i = start;
while(i < end){
if(i+1 < end && nums[i] + 1 == nums[i+1]){
}else{
//如果不相等,出现断
t_e = nums[i];
string s;
if(t_e == t_s){
s+= to_string(t_s);
}else{
s+= to_string(t_s);
s+= "->";
s+= to_string(t_e);
}
res.push_back(s);
//更新新的起始地址
t_s = nums[i+1];
}
i++;
}
return res;
}
};