解法:
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums)
{
vector<string> res;
string tmp;
if (nums.empty()){
return res;
}
bool begin = true;
for (int i = 0; i < nums.size() - 1; ++i) {
if (begin) {
if (nums[i] + 1 == nums[i+1]) {
tmp += to_string(nums[i]);
tmp += "->";
begin = false;
}else{
tmp += to_string(nums[i]);
res.push_back(tmp);
tmp.clear();
}
}else {
if (nums[i] + 1 == nums[i+1]) {
continue;
}else {
tmp += to_string(nums[i]);
res.push_back(tmp);
begin = true;
tmp.clear();
}
}
}
tmp += to_string(nums.back());
res.push_back(tmp);
return res;
}
};
总结:
计算时间复杂度O(N),空间复杂度O(1)。