228 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: A range in this case is considered to be an integer continuous sequence.

vector<string> summaryRanges(vector<int>& nums) 
{
    vector<string> ranges;
    ranges.reserve(nums.size() / 2);

    int i, j;
    for (i = 0; i < nums.size(); i++)
    {
        int start = nums[i];
        for (j = i; j < nums.size() - 1 && nums[j + 1] == nums[j] + 1; j++) {};
        int end = nums[j];

        if (start == end) ranges.push_back(to_string(start));
        else ranges.push_back(to_string(start) + "->" + to_string(end));

        i = j;
    }

    return ranges;
}

int main()
{
    vector<int> nums = { 0,1,2,4,5,7 };
    print(summaryRanges(nums));

    nums = { 1,3,4,5,6,20,100,100, 101,300 };
    print(summaryRanges(nums));
}

Last updated