Leetcode Leetcode 228. Summary interval

Topic:

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:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The interval range is:
[0,2]- -> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example_2:

Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The interval range is:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

Example_3:

Input: nums = []
Output: []

Example_4:

Input: nums = [-1]
Output: ["-1"]

Example_5:

Input: nums = [0]
Output: ["0"]

Solution:

Following the idea of Question 830 ,
we can traverse the sequence
and record the length of the current growth array.
If the next character is different from the current character plus one, or has been enumerated to the end of the string,
it means that the current character is the end of the current group
every time the current group is found. when the tail
if the packet length reaches 2, we added to the result in accordance with the subject res format
if the packet length is not reached 2 (1), we just added res quotes in
the last complete return res

Code:

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        res = []
        n = len(nums)
        count = 1

        if n == 0:
            return nums

        for i in range(n):
            if i == n - 1 or nums[i]  + 1 != nums[i + 1] :
                if count >= 2:
                    res.append("{}->{}".format(nums[i - count + 1], nums[i]))
                else:
                    res.append("{}".format(nums[i]))
                count = 1

            else:
                count += 1
        
        return res

Answer:
The effect is acceptable

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112424077