您的位置:首页 > 其它

228. Summary Ranges

2016-02-21 14:07 267 查看
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"].


Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question
Solution:

class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> tmp;
int i = 0;
int pre = 0;
if(nums.empty()) return tmp;
pre = nums[0];
for(;i<nums.size();i++){
if(i+1==nums.size()){
if(pre==nums[i]) {tmp.push_back(to_string(pre));}
else {
tmp.push_back(to_string(pre)+"->"+to_string(nums[i]));
}

return tmp;
}
else{
if(nums[i+1]==nums[i]+1) {}
else {
if(pre==nums[i]) {tmp.push_back(to_string(pre));}
else{
tmp.push_back(to_string(pre)+"->"+to_string(nums[i]));
}
pre = nums[i+1];
}
}
}

}
};
心得:主要考虑corner,程序写的比较繁琐,但逻辑比较清楚

运行速度:快
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: