码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode228——Summary Ranges

时间:2015-07-09 00:51:28      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:leetcode

一个月没写C++代码,现在感到好陌生

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.

vector<string> summaryRanges(vector<int>& nums) {
    vector<string> vs;
    if (nums.size() == 0) return vs; 
    int begin = nums[0];
    int end = nums[0];
    char temp[256];
    for (int i = 1; i < nums.size(); i++){
        if (nums[i] != end+1) {
            if (begin != end) {
                sprintf(temp, "%d->%d", begin, end);
            }else {
                sprintf(temp, "%d",end);
            }
            string s(temp);
            vs.push_back(s);
            begin = nums[i];
        }
        end = nums[i];
    }
    if (begin != end) {
        sprintf(temp, "%d->%d", begin, end);
    }else {
        sprintf(temp, "%d",end);
    }
    string s(temp);
    vs.push_back(s);
    return vs;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode228——Summary Ranges

标签:leetcode

原文地址:http://blog.csdn.net/booirror/article/details/46810977

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!