这是Array里的第一题。题意是找出排序好的数组的数字范围集合。
记录的知识点:
1, c++中将数字转化为字符串
stringstream ss;
ss<<num
string tem = num.str();
2, vector初始化,添加元素
vector<string> vecStr;
string tem;
vecStr.push_back(tem);
3, 遍历vector
vector<string>::iterator iter;
for(iter = vecStr.begin(); iter != vecStr.end(); iter++){
cout<< *iter;
}
这道题目的代码如下:
vector<string> summaryRanges(vector<int>& nums) {
int n = (int)nums.size();
vector<string> rangeStr;
int i = 0,j = 0;
while (j <= n - 1) {
if (nums[j]+1 != nums[j+1]) {
string tem ;
if (i != j ) {
stringstream lefts ;
lefts << nums[i];
tem = lefts.str();
tem = tem + "->";
stringstream rights ;
rights << nums[j];
tem = tem + rights.str();
}else{
stringstream lefts ;
lefts << nums[i];
tem = lefts.str();
}
rangeStr.push_back(tem);
i = j+1;
}
j++;
}
if (i < n ) {
if ( i+1 == j) {
stringstream lefts ;
lefts << nums[i];
rangeStr.push_back(lefts.str());
}else{
string tem ;
stringstream lefts ;
lefts << nums[i];
tem = lefts.str();
tem = tem + "->";
stringstream rights ;
rights << nums[j-1];
tem = tem + rights.str();
rangeStr.push_back(tem);
}
}
return rangeStr;
}