228. Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input:  [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

next為下一個在數列裡要找的數,一開始初始化為數列第一個數。如果數列裡的樹為連續的就把他們接上。

vector<string> summaryRanges(vector<int>& nums) { // time: O(n); space: O(n)
    vector<string> res;
    if (nums.empty()) return res;
    int next = nums.front();
    for (int i = 0; i < nums.size(); ++i) {
        while (i + 1 < nums.size() && nums[i] + 1 == nums[i + 1]) ++i;
        string tmp;
        if (nums[i] != next) {
            tmp = to_string(next) + "->" + to_string(nums[i]);
        } else {
            tmp = to_string(next);
        }
        res.push_back(tmp);
        // no need to update if the element is the last one
        if (i != nums.size() - 1) next = nums[i + 1];
    }
    return res;
}

Last updated

Was this helpful?