題目
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;
}
};