# 228. Summary Ranges

### 228. Summary Ranges

Total Accepted: 36554 Total Submissions: 159532 Difficulty: Easy

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> result;
int i=0;
while(i<nums.size())
{
string ans=to_string(nums[i]);
bool flag=false;
//一，添加箭头
if( ++i < nums.size() && nums[i]==(nums[i-1]+1) )//箭头的依据
{
ans.append("->");
flag=true;//箭头已经添加
}
//二，寻找箭头后面那个数字
while(flag && i<nums.size())
{
if(nums[i]!=nums[i-1]+1)
break;
i++;
}
//三，追加箭头后面的数
if(flag)
ans.append(to_string(nums[i-1]));
result.push_back(ans);
}
return result;
}
};

（双指针）

class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
for (int i = 0; i < nums.size();) //遍历数组
{
int start = i, end = i;//起始与终止变量
while (end + 1 < nums.size() && nums[end+1] == nums[end] + 1) //寻找终止变量的位置
end++;
if (end > start)
result.push_back(to_string(nums[start]) + "->" + to_string(nums[end]));
else
result.push_back(to_string(nums[start]));
i = end+1;
}
return result;
}
};