Summary interval

Given an ordered integer array nums nums with no repeated elementsnums

Returns a list of the smallest ordered range ranges that happen to cover all the numbers in the array. In other words, nums numsEach element of n u m s is exactly covered by a certain range, and there is nonums numsthat belongs to a certain rangen u m s numberxxx

Each interval range in the list [a, b] [a, b][a,b ] should be output in the following format:

"a->b"If a != b
"a", ifa == 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"]

prompt:

0 < = n u m s . l e n g t h < = 20 0 <= nums.length <= 20 0<=nums.length<=20
− 2 3 1 < = n u m s [ i ] < = 2 31 − 1 -2^31 <= nums[i] <= 2^{31} - 1 231<=nums[i]<=2311
n u m s nums All values ​​in n u m s are different from each other
nums numsn u m s in ascending order

class Solution {
    
    
public:
    vector<string> summaryRanges(vector<int>& nums) {
    
    
        vector<string>res;
        int i=0;
        int n=nums.size();
        while (i<n){
    
    
            int l=i;
            i++;
            while (i<n&&nums[i]==nums[i-1]+1){
    
    
                i++;
            }
            int r=i-1;
            string tmp=to_string(nums[l]);
            if (l<r){
    
    
                tmp+="->";
                tmp+=to_string(nums[r]);
            }
            res.push_back(tmp);
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43601103/article/details/112434695