Leikou punch card 2021.1.10 summary interval problem

Problem:
Given an ordered integer array nums with no repeated elements.
Returns a list of the smallest ordered range ranges that happen to cover all the numbers in the array. In other words, each element of nums is exactly covered by a certain range, and there is no number x belonging to a certain range but not belonging to nums.
Each interval range [a,b] in the list should be output in the following format:
"a->b", if a != b
"a", if a == b
Example 1:

输入:nums = [0,1,2,4,5,7]
输出:["0->2","4->5","7"]
解释:区间范围是:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example 2:

输入:nums = [0,2,3,4,6,8,9]
输出:["0","2->4","6","8->9"]
解释:区间范围是:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

Example 3:

输入:nums = []
输出:[]

Example 4:

输入:nums = [-1]
输出:["-1"]

Example 5:

输入:nums = [0]
输出:["0"]

Idea:
Just traverse once

Code:

class Solution {
    
    
public:
    vector<string> summaryRanges(vector<int>& nums) {
    
    
        vector<string> ans;
        int left = 0;

        for (int i = 0; i < nums.size(); ++i) {
    
    
            if (i + 1 == nums.size() || nums[i] + 1 != nums[i + 1]) {
    
    
                ans.push_back(std::to_string(nums[left]) + (left == i ? "" : "->" + std::to_string(nums[i])));
                left = i + 1;
            }
        }

        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45780132/article/details/112424168