题意
求数组内所有连续的范围。
思路
用两个指针i和j,分别指向每个范围的开始位置和结束位置就好。然后去遍历数组。
string to_string(int x)
:将x转化为一个string返回。
细节
注意只有一个元素或者j指向最后一个元素的情况。
因此我们在遍历数组的时候,可以用j == n作为终止条件,并且终止条件特判一下避免出错。
代码
class Solution {
private:
vector<string> ans;
int n;
public:
void convert(int x, int y) {
string s = to_string(x);
if (x != y) {
s += "->";
s += to_string(y);
}
ans.push_back(s);
}
vector<string> summaryRanges(vector<int>& nums) {
n = nums.size();
if (n) {
int i = 0, j = 1;
while (j <= n) {
if (j == n) convert(nums[i], nums[j - 1]);
else {
if (nums[j] != nums[j - 1] + 1) {
convert(nums[i], nums[j - 1]);
i = j;
}
}
j++;
}
}
return ans;
}
};