题目:
Given a sorted integer array without duplicates, return the summary of its ranges.
思路:
思路很简单,就是从头到尾遍历一遍元素,看看是否与前一个元素差1。需要注意的是int的溢出问题,凡是涉及到元素运算的地方,都要先将元素转换成long类型,防止溢出。
代码实现:
class Solution {
public:
string itos(int i){
string str;
stringstream stream;
stream << i;
stream >> str;
return str;
}
vector<string> summaryRanges(vector<int>& nums) {
if (nums.size() <= 0){
return {};
}
vector<string> ret;
int begin = 0;
for (int i = 1; i < nums.size(); ++i){
long pre_num = nums[i-1];
long cur_num = nums[i];
if (cur_num-pre_num == 1){
continue ;
}else{
if (begin == i-1){
string t = itos(nums[begin]);
ret.push_back(t);
}else{
string t = itos(nums[begin])+"->"+itos(nums[i-1]);
ret.push_back(t);
}
begin = i;
}
}
if (begin == nums.size()-1){
string t = itos(nums[begin]);
ret.push_back(t);
}else{
string t = itos(nums[begin])+"->"+itos(nums[nums.size()-1]);
ret.push_back(t);
}
return ret;
}
};
discuss:
// 常规思路:每次循环都寻找连续数字序列。
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
for (int i = 0; i < nums.size(); ++i){
int num = nums[i];
while (i + 1 < nums.size() && nums[i] == nums[i + 1] - 1) ++i; // 把连续的一串顺子找出来
if (nums[i] != num) // 存在一个范围
res.push_back(to_string(num) + "->" + to_string(nums[i]));
else // 只有一个孤立地数字
res.push_back(to_string(nums[i]));
}
return res;
}
};