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

【LeetCode】228. Summary Ranges

时间:2015-07-08 22:16:05      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

Summary Ranges

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.

 

使用low和high记录连续区间,若只有一个元素,则无需加箭头。

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

技术分享

【LeetCode】228. Summary Ranges

标签:

原文地址:http://www.cnblogs.com/ganganloveu/p/4631342.html

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