Simple Java code


  • 28
    C
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            List<String> list = new ArrayList<String>();
            if(nums == null) return list;
            int n = nums.length;
            for(int i = 0; i <= n; i++) {
                int lt = (i == 0) ? lower : nums[i - 1] + 1;
                int gt = (i == n) ? upper : nums[i] - 1;
                addRange(list, lt, gt);
            }
            return list;
        }
        private void addRange(List<String> list, int lo, int hi) {
            if(lo > hi) return;
            else if(lo == hi) list.add(String.valueOf(lo));
            else list.add(lo + "->" + hi);
        }

  • 0
    H

    Excellent!!!


  • 0
    Z

    @Charliy there is a bug inside. Try this case [0, 3, 5, 7] 4, 9


  • 0
    J

    @zhe11 "where the range of elements are [lower, upper] inclusive" :)


  • 4
    K

    there is an overflow bug


  • 0
    S
    This post is deleted!

  • 0
    C

    First of all, when nums == null, I think list should contain range of lower to upper, and second there's overflow problem, oh god that Integer.MAX_VALUE is annoying!


  • 0
    S

    This solution no long works...

    It's frustrative that they add a lot of special number in the test case, we need to consisder integer overflow now.

    I


  • 1
    S

    Excellent solution! I modify your code to cover the corner cases.

     public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        List<String> list = new ArrayList<String>();
        if(nums == null) return list;
        int n = nums.length;
        for(int i = 0; i <= n; i++) {
            int lt =0, gt=0;
            
            if(i==0)
                lt = lower;
            else
                if(nums[i-1]==Integer.MAX_VALUE)
                    break;
                else
                    lt = nums[i-1]+1;
            
            if(i==n)
                gt = upper;
            else
                if(nums[i]==Integer.MIN_VALUE)
                    continue;
                else
                    gt = nums[i]-1;
    
            addRange(list, lt, gt);
        }
        return list;
    }
    
    private void addRange(List<String> list, int lo, int hi) {
        if(lo > hi) return;
        else if(lo == hi) list.add(String.valueOf(lo));
        else list.add(lo + "->" + hi);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.