Thursday, June 25, 2015

[LeetCode] 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"].
Note: Overflow.
class Solution {
    string getRange(int start, int end)
    {
        if(start == end) return to_string(start);
        return to_string(start) + "->" + to_string(end);
    }
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;
        if(nums.empty()) return res;
        
        long start = nums[0];
        long end = start;
        
        for(int i=1;i<nums.size();i++)
        {
            if(nums[i] - end >1)
            {
                res.push_back(getRange(start, end));
                start = nums[i];
                end = start;
            }
            else
            {
                end = nums[i];
            }
        }
        res.push_back(getRange(start, end));
        return res;
    }
};