Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7] Output: ["0->2","4->5","7"]
Example 2:
Input: [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"]
分析:
1.定义两个边界l,r。l为左边界,r为右边界,如果i位置与r位置相邻,将r设置为i;否则,重新设置左右边界,并将上一个存放
2.to_string():将数值转换为字符串
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
string s;
vector<string>v;
if(nums.size()==0) return v;
int cnt=0,l=0,r=0;
for(int i=1;i<nums.size();i++){
if((nums[i]-nums[r])==1){
cnt++;
r=i;
}else{
s=to_string(nums[l]);
if(cnt>0) s+="->"+to_string(nums[r]);
v.push_back(s);
l=i;r=i;cnt=0;
}
}
s=to_string(nums[l]);
if(cnt>0) s=s+"->"+to_string(nums[r]);
v.push_back(s);
return v;
}
};