LeetCode Missing Ranges

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

题目:

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

For example, given [0, 1, 3, 50, 75]lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].

题解:

与Summary Ranges相似.

expected是当前期待的数字, 初始化为lower.

若是expected不等于nums[i]时就说明出现了missing range, 要分类加结果.

看最后一个元素是否是upper, 若不是,还需要加最后一段.

Time Complexity: O(n). Space: O(1). 不考虑res大小.

AC Java:

 1 public class Solution {
 2     public List<String> findMissingRanges(int[] nums, int lower, int upper) {
 3         List<String> res = new ArrayList<String>();
 4         if(nums == null || nums.length == 0){
 5             if(lower == upper){
 6                 res.add(String.valueOf(lower));
 7                 return res;
 8             }else{
 9                 res.add(String.valueOf(lower) + "->" + String.valueOf(upper));
10                 return res;
11             }
12         }
13         
14         //最开始的expeted number 是 lower
15         int expected = lower;
16         for(int i = 0; i<nums.length; i++){
17             if(nums[i] != expected){ //若是出现expected 不等于 nums[i], 就该加missing range 到res中了
18                 if(expected + 1 == nums[i]){
19                     res.add(String.valueOf(expected));
20                 }else{
21                     res.add(String.valueOf(expected) + "->" + String.valueOf(nums[i]-1));
22                 }
23             }
24             //不论expected 是否等于 nums[i], 都更新expected 到 num[i]+1.
25             expected = nums[i]+1;
26             
27             //到了nums最后一个还是没有到达upper
28             if(i == nums.length-1 && nums[i] != upper){
29                 if(nums[i] + 1 == upper){
30                     res.add(String.valueOf(nums[i]+1));
31                 }else{
32                     res.add(String.valueOf(nums[i]+1) + "->" + String.valueOf(upper));
33                 }
34             }
35         }
36         
37         return res;
38     }
39 }

 

你可能感兴趣的:(LeetCode Missing Ranges)