加载中...
228-汇总区间(Summary Ranges)
发表于:2021-12-03 | 分类: 简单
字数统计: 490 | 阅读时长: 2分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/summary-ranges

英文原文

You are given a sorted unique integer array nums.

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"

Example 3:

Input: nums = []
Output: []

Example 4:

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

Example 5:

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

 

Constraints:

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

中文题目

给定一个无重复元素的有序整数数组 nums

返回 恰好覆盖数组中所有数字最小有序 区间范围列表。也就是说,nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums 的数字 x

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

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

 

示例 1:

输入:nums = [0,1,2,4,5,7]
输出:["0->2","4->5","7"]
解释:区间范围是:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

示例 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"

示例 3:

输入:nums = []
输出:[]

示例 4:

输入:nums = [-1]
输出:["-1"]

示例 5:

输入:nums = [0]
输出:["0"]

 

提示:

  • 0 <= nums.length <= 20
  • -231 <= nums[i] <= 231 - 1
  • nums 中的所有值都 互不相同
  • nums 按升序排列

通过代码

高赞题解

一、题目分析

题意: 将输入数组切分成连续递增的几段,将每段按照指定格式写入结果列表。

示例:
输入:nums = [0, 1, 2, 4, 5, 7]
输出:[“0->2”, “4->5”, “7”]

分析: 使用 双指针i 指向每个区间的起始位置,ji 开始向后遍历直到不满足连续递增(或 j 达到数组边界),则当前区间结束;然后将 i 指向更新为 j + 1,作为下一个区间的开始位置,j 继续向后遍历找下一个区间的结束位置,如此循环,直到输入数组遍历完毕。

二、代码实现

[]
class Solution { public List<String> summaryRanges(int[] nums) { List<String> res = new ArrayList<>(); // i 初始指向第 1 个区间的起始位置 int i = 0; for (int j = 0; j < nums.length; j++) { // j 向后遍历,直到不满足连续递增(即 nums[j] + 1 != nums[j + 1]) // 或者 j 达到数组边界,则当前连续递增区间 [i, j] 遍历完毕,将其写入结果列表。 if (j + 1 == nums.length || nums[j] + 1 != nums[j + 1]) { // 将当前区间 [i, j] 写入结果列表 StringBuilder sb = new StringBuilder(); sb.append(nums[i]); if (i != j) { sb.append("->").append(nums[j]); } res.add(sb.toString()); // 将 i 指向更新为 j + 1,作为下一个区间的起始位置 i = j + 1; } } return res; } }

时间复杂度: $O(N)$

统计信息

通过次数 提交次数 AC比率
60581 104932 57.7%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言

相似题目

题目 难度
缺失的区间 简单
将数据流变为多个不相交区间 困难
上一篇:
227-基本计算器 II(Basic Calculator II)
下一篇:
229-求众数 II(Majority Element II)
本文目录
本文目录