Leetcode: Summary Ranges

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;
    }
};

 

posted @ 2015-06-27 02:06  Justin.cn  阅读(224)  评论(0编辑  收藏  举报