https://leetcode.com/problems/summary-ranges/
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"].
题很简单,如果是自己写整数转换字符串函数的话会出现一下两个问题
a.可能出现负数
b.判断数字是否连续的时候可能出现超出整形的表示范围
为了方便最后一个如果出现只有一个数字范围的情况,我将原数组中最后一个数复制了一个放在了数组最后。
代码:
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ans;
if (nums.empty())return ans;
nums.push_back(nums[nums.size() - 1]);
for (int i = 0; i < nums.size(); ++i)
{
string str = itos(nums[i]);
for (int j = i + 1; j < nums.size(); ++j)
{
if ((long long)nums[i] + (j - i) != nums[j])
{
if (i + 1 == j)
{
ans.push_back(str);
i = j - 1;
break;
}
else
{
ans.push_back(str + "->" + itos(nums[j - 1]));
i = j - 1;
break;
}
}
}
}
return ans;
}
string itos(long long i)
{
string str = "";
int sign = true;
if (i < 0)sign = false, i = -i;
while (i)
{
str = char(((i % 10) + '0')) + str;
i /= 10;
}
if (str == "")str.push_back('0');
return sign ? str : "-" + str;
}
};
第一次写,有点紧张.以后会坚持记录自己的code成长历程