欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 资讯 > LeetCode 228 Summary Ranges 解题思路和python代码

LeetCode 228 Summary Ranges 解题思路和python代码

2024/11/13 4:33:43 来源:https://blog.csdn.net/weixin_57266891/article/details/142731752  浏览:    关键词:LeetCode 228 Summary Ranges 解题思路和python代码

题目
You are given a sorted unique integer array nums.

A range [a,b] is the set of all integers from a to b (inclusive).

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

“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 ranges are:
[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 ranges are:
[0,0] --> “0”
[2,4] --> “2->4”
[6,6] --> “6”
[8,9] --> “8->9”

Constraints:

0 <= nums.length <= 20
-231 <= nums[i] <= 231 - 1
All the values of nums are unique.
nums is sorted in ascending order.

解题思路
我们从数组第一个数字开始,初始化一个变量start表示当前范围的起始值。
遍历数组中的每一个元素,如果当前元素 nums[i] 与前一个元素 nums[i-1] 不连续,那么我们将范围 [start, nums[i-1]] 添加到结果中,并更新 start 为当前元素 nums[i]。
遍历结束后,将最后一个范围添加到结果中。

class Solution:def summaryRanges(self, nums: List[int]) -> List[str]:result = []if not nums:return resultstart = nums[0]for i in range(1, len(nums)):if nums[i] != nums[i-1] + 1:if start == nums[i-1]:result.append(f"{start}")else:result.append(f"{start}->{nums[i-1]}")start = nums[i]if start == nums[-1]:result.append(f"{nums[-1]}")else:result.append(f"{start}->{nums[-1]}")return result

time complexity为O(n)。
注意,使用python3。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com