【LeetCode】228. Summary Ranges

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

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