LeetCode OJ 之 Summary Ranges
2015-07-10 11:20
232 查看
题目:
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given
把连续的转化成0->2这种形式存储在string里。
思路:
代码:
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums)
{
vector<string> result;
string path;
int len = nums.size();
if(len == 0)
return result;
int i = 0 ;
for(; i < len-1 ; i++)
{
if(nums[i] != nums[i+1] - 1)
{
//如果path之前非空,则加上->,如果为空,则只有一个字符
if(path != "")
path += "->";
path += to_string(nums[i]);
result.push_back(path);
path.clear();
}
else
//如果path之前为空,则把当前数字作为开头
if(path == "")
path = to_string(nums[i]);
}
//加上最后一个数字
if(path != "")
path += "->";
path += to_string(nums[i]);
result.push_back(path);
return result;
}
};
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"].
把连续的转化成0->2这种形式存储在string里。
思路:
代码:
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums)
{
vector<string> result;
string path;
int len = nums.size();
if(len == 0)
return result;
int i = 0 ;
for(; i < len-1 ; i++)
{
if(nums[i] != nums[i+1] - 1)
{
//如果path之前非空,则加上->,如果为空,则只有一个字符
if(path != "")
path += "->";
path += to_string(nums[i]);
result.push_back(path);
path.clear();
}
else
//如果path之前为空,则把当前数字作为开头
if(path == "")
path = to_string(nums[i]);
}
//加上最后一个数字
if(path != "")
path += "->";
path += to_string(nums[i]);
result.push_back(path);
return result;
}
};
相关文章推荐
- simhash
- 一分钟理解APM,把流失的用户找回来
- Firefox Setup 32.0.1 32位
- C++ Socket编程步骤
- servlet容器与web容器的概念
- ios tableviewcell分割线左边有空白
- 菜鸟练习PAT(九)
- hdu 1235 统计同成绩学生人数
- C#-简单的定时器(C# ConsoleApp) ---ShinePans
- servlet容器与web容器的概念
- Python学习之初识Python
- 在Java内存模型中测试并发程序代码
- LINQ动态条件查询(一)
- TextView属性
- php缓存生成静态页
- Xcode 配置文件 xcconfig 使用实践
- Mybatis 错误信息:Parameter index out of range
- BOM头是什么呢?
- C++ 对进程各种操作函数
- Android_调用ffmpeg_把截取视频保存为ppm文件