力扣 leetcode 228. 汇总区间

Topic:

给定一个无重复元素的有序整数数组 nums 。
返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表。也就是说,nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums 的数字 x 。
列表中的每个区间范围 [a,b] 应该按如下格式输出:
“a->b” ,如果 a != b
“a” ,如果 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”]

Solution:

仿照830题的思路
我们可以遍历该序列
并记录当前增长数组的长度
如果下一个字符与当前字符加一不同,或者已经枚举到字符串尾部
就说明当前字符为当前分组的尾部
每次找到当前分组的尾部时
如果该分组长度达到 2,我们就按照题目格式加入到结果res中
如果分组长度不达到2(为1),我们就直接加上引号加入res中
最后返回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:
效果尚可

猜你喜欢

转载自blog.csdn.net/weixin_50791900/article/details/112424077