LeetCode 163. 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.

posted @ 2016-03-21 11:33  Dylan_Java_NYC  阅读(532)  评论(0编辑  收藏  举报