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"].
分析:第一个问题,为什么所有测试用例都没有判断降序的情况?题目只是说已经排序的数组而已,因为增序和降序处理方法是不一样的。
遇到的第一个问题是,如何将数字转换成字符串??to_string()
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result(0);
if(nums.empty()){
return result;
}
vector<int>::iterator iter=nums.begin();
//if(*iter<*(iter+1)){ //为什么不用判断给定的数组是增序还是降序??
for(vector<int>::iterator iter1=nums.begin();iter1!=nums.end();iter1++){
if(iter1==nums.end()-1){
if(iter==iter1){
string temp=to_string(*iter);
result.push_back(temp);
break;
}
else{
string temp=to_string(*iter)+"->"+to_string(*iter1);
result.push_back(temp);
break;
}
}
if(*iter1+1!=*(iter1+1)){
if(iter==iter1){
string temp=to_string(*iter);
result.push_back(temp);
iter=iter1+1;
}
else{
string temp=to_string(*iter)+"->"+to_string(*iter1);
result.push_back(temp);
iter=iter1+1;
}
}
}
return result;
// }
}
};