LeetCode Missing Ranges

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Missing Ranges相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/missing-ranges/

题目:

Given a sorted integer array nums, where the range of elements are in the inclusive range [lowerupper], return its missing ranges.

Example:

Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99,
Output: ["2", "4->49", "51->74", "76->99"]

题解:

If nums is null or empty, just add getRange(lower, upper).

Otherwise, first add range between lower and nums[0].

Then add missing range within nums.

Last, add range between nums[nums.length - 1] and upper.

Time Complexity: O(n). n = nums.length.

Space: O(1). regardless res.

AC Java:

 1 class Solution {
 2     public List<String> findMissingRanges(int[] nums, int lower, int upper) {
 3         List<String> res = new ArrayList<>();
 4         if(nums == null || nums.length == 0){
 5             res.add(getRange(lower, upper));
 6             return res;
 7         }
 8         
 9         if(lower < nums[0]){
10             res.add(getRange(lower, nums[0] - 1));
11         }
12         
13         for(int i = 1; i<nums.length; i++){
14             if(nums[i - 1] != nums[i] && nums[i - 1] + 1 != nums[i]){
15                 res.add(getRange(nums[i - 1] + 1, nums[i] - 1));
16             }
17         }
18         
19         if(nums[nums.length - 1] < upper){
20             res.add(getRange(nums[nums.length - 1] + 1, upper));
21         }
22         
23         return res;
24     }
25     
26     private String getRange(int l, int r){
27         if(l == r){
28             return "" + l;
29         }
30         
31         return l + "->" + r;
32     }
33 }

类似Summary RangesData Stream as Disjoint Intervals.

以上是关于LeetCode Missing Ranges的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 163. Missing Ranges 缺失区间

163.Missing Ranges

[Locked] Missing Ranges

Missing Ranges 解答

163. Missing Ranges

LC 163. Missing Ranges