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

Leetcode: Summary Ranges

时间:2015-06-27 06:23:31      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Summary Ranges

Total Accepted: 2073 Total Submissions: 9344

 
 

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.

 

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> ret;
        if (nums.empty())    return ret;
        nums.push_back(nums[0]);
        long last = nums[0];
        int begin = last;
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] != last + 1) {
                string range = last == begin ? to_string(last) : to_string(begin) + "->" + to_string(last);
                ret.push_back(range);
                begin = nums[i];
            }
            last = nums[i];
        }


        return ret;
    }
};

 

Leetcode: Summary Ranges

标签:

原文地址:http://www.cnblogs.com/ydlme/p/4603552.html

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