题目
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”].
解答
这一题很简答,主要是把数字转化为字符串,可以使用itoa,也可以使用to_string,但是在leetcode上使用itoa,貌似没有包含这个,就自己写了一个。
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
const int size_n=nums.size();
if(size_n==0) return res;
for(int i=0;i<size_n;){
int start=i,end=i;
while(end+1<size_n&&nums[end]+1==nums[end+1]) end++;
if(end>start) res.push_back(to_string(nums[start])+"->"+to_string(nums[end]));
else res.push_back(to_string(nums[start]));
i=end+1;
}
return res;
}
};
class Solution1 {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
if (nums.size() == 0) return res;
int i = 0;
string end_s = "";
string res_temp;
while (i<=nums.size() - 1)
{
int start = i;
char p[20];
itoa(nums[start], p, 10);
res_temp = p;
int end = i;
while (i<nums.size() - 1&&nums[i + 1] - nums[i] == 1)
{
i++;
end = i;
}
i++;
if(start!=end)
{
itoa(nums[end], p, 10);
end_s = p;
res_temp = res_temp + "->";
res_temp = res_temp + end_s;
}
res.push_back(res_temp);
}
return res;
}
private:
void itoa(int num, char *str, int radix)//这里不考虑其他进制的
{
char index[] = "0123456789ABCDEF";
unsigned unum;
int i = 0, j, k;
if (radix == 10 && num<0)//10进制负数
{
unum = (unsigned)-num;//unsigned是为了考虑 INT_MIN这种情况
str[i++] = '-';
}
else
unum = (unsigned)num;
do {
str[i++] = index[unum % (unsigned)radix];
unum /= radix;
} while (unum);
str[i] = '\0';
if (str[0] == '-') k = 1;
else k = 0;
char temp;
for (j = k; j<=(i - 1)/ 2; j++)//反转
{
temp = str[j];
str[j] = str[i - 1 + k - j];
str[i - 1 + k - j] = temp;
}
}
};