[LeetCode] 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

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.

汇总区间。

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

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/summary-ranges
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

影子题163。这个题不涉及什么算法或者思路,注意到如果是区间,那么区间内的数字一定要是连续的,否则就要开始结算区间了。代码中如果跳出 while 循环的时候,一开始的num == 现在的 nums[i] 那说明这个数字是单独存在的。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public List<String> summaryRanges(int[] nums) {
 3         List<String> res = new ArrayList<>();
 4         if (nums == null || nums.length == 0) {
 5             return res;
 6         }
 7         for (int i = 0; i < nums.length; i++) {
 8             // range start
 9             int num = nums[i];
10             while (i < nums.length - 1 && nums[i] + 1 == nums[i + 1]) {
11                 i++;
12             }
13             // 跳出while循环的时候,nums[i]应该是range的end
14             if (num != nums[i]) {
15                 res.add(num + "->" + nums[i]);
16             } else {
17                 res.add(num + "");
18             }
19         }
20         return res;
21     }
22 }

 

相关题目

163. Missing Ranges

228. Summary Ranges

LeetCode 题目总结

posted @ 2020-05-13 12:30  CNoodle  阅读(164)  评论(0编辑  收藏  举报