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"].

这道题目的意思给定排序的数组,求出数组中元素表示的范围,要满足 [s, e],其中i属于上述的范围且nums[i] = nums[i - 1] + 1;

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string>  res;

        for(int i = 0; i < nums.size();){
            int e = i;
            while(e + 1< nums.size() && nums[e + 1] == nums[e] + 1)
                e++;

            if(e > i)   res.push_back(to_string(nums[i]) + "->" + to_string(nums[e]));
            else    res.push_back(to_string(nums[i]));

            i = e + 1;
        }
        return res;
    }
};

results matching ""

    No results matching ""