【LeetCode 面试经典150题】228. Summary Ranges 汇总区间

228. Summary Ranges

题目大意

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

中文释义

给你一个排序好的且不重复的整数数组 nums

一个范围 [a,b] 是从 ab 的所有整数的集合(包括 ab)。

返回一个最小的排序范围列表,该列表完全覆盖数组中的所有数字。也就是说,nums 的每个元素都恰好被列表中的一个范围所覆盖,且不存在一个整数 x 被范围包含但不在 nums 中。

列表中的每个范围 [a,b] 应该按照以下格式输出:

  • 如果 a != b,输出 "a->b"
  • 如果 a == b,输出 "a"

示例

Example 1:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 范围为:
[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: 范围为:
[0,0] --> “0”
[2,4] --> “2->4”
[6,6] --> “6”
[8,9] --> “8->9”

限制条件

  • 0 <= nums.length <= 20
  • -2^31 <= nums[i] <= 2^31 - 1
  • nums 中的所有值都是唯一的。
  • nums 按升序排序。

解题思路

方法

即从给定的排序数组 nums 中找出并返回表示连续区间的字符串列表。
方法使用了双指针技术。

  1. 初始化

    • 创建一个空的字符串数组 ans 用于存储结果。
  2. 使用双指针遍历数组

    • 使用两个指针 startend,其中 start 指示当前连续区间的开始,而 end 用于探索区间的结束。
    • 遍历数组,对于每个位置 end
      • 检查当前位置是否是连续区间的结束,这通过比较 nums[end]nums[end + 1] 来判断。如果 end + 1 是数组的末尾,或者 nums[end + 1]nums[end] 不连续,则当前区间结束。
      • 根据区间的起始和结束位置,构造区间字符串。如果 startend 相同,表示区间只包含一个元素,直接使用 nums[start] 的值。如果不同,则构造一个 “start->end” 的字符串。
      • 将构造的区间字符串添加到结果数组 ans 中。
      • 更新 start 为下一个可能区间的起点。
  3. 返回结果

    • 完成遍历后,返回包含所有连续区间的字符串数组 ans

代码

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> ans;
        for (int start = 0, end = 0; end < nums.size(); end++) {
            if (end + 1 == nums.size() || (long)nums[end + 1] - nums[end] != 1) {
                if (start == end) {
                    ans.push_back(to_string(nums[start]));
                } else {
                    ans.push_back(to_string(nums[start]) + "->" + to_string(nums[end]));
                }
                start = end + 1;
            }
        }
        return ans;
    }
};
  • 11
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值