水平有限,不足之处还望指正。
题目:
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"].
题目意思:
给出一个有序无重复整数数组,返回数组的有序片段。
即将数组中连续的数字(后面数字比其前面数字大1)作为一个片段转化成一个字符串,用->连接起来;单独的数字作为一个字符串不需要用->;
解题思路:
首先理解这个题目的意思,然后搞清楚怎样将整数转化为字符串,之后就很容易了。
用两个指针start,end指向整数数组,如果nums[i] == end + 1,移动end,否则将从start开始到end结束的整数段转化为一字符串。
这里要注意start与end知否为同一数据:代表不同数据时需加上符号 "->".
代码如下:
string IntToString(int start, int end)
{
char temp[20];
if (start == end)
{
sprintf(temp, "%d", start);
}
else
{
sprintf(temp, "%d->%d", start, end);
}
return string(temp);
}
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums)
{
vector<string> result;
if (nums.size() < 1)
return result;
int start = nums[0], end = nums[0];
for (int i = 1; i < nums.size(); i++)
{
if (nums[i] == end + 1)
{
end = nums[i];
}
else
{
result.push_back(IntToString(start, end));
start = end = nums[i];
}
}
result.push_back(IntToString(start, end));
return result;
}
};