Java solution with explanation


  • 0
    P
    public class Solution {
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        List<String> res = new ArrayList<String>();
        if(nums == null)
            return res;
        
        //empty array
        if(nums.length == 0)
        {
            if(upper - lower == 0)
            {
                String cur = "" + upper;
                res.add(cur);
            }
            else
            {
                String cur = "" + lower + "->" + upper;
                res.add(cur);
            }
            
            return res;
        }
        
        //lower bound case, before array start
        if(nums[0] > lower)
        {
            if(nums[0] - lower == 1)
            {
                String cur = "" + lower;
                res.add(cur);
            }
            else
            {
                String cur = "" + lower + "->" + (nums[0] - 1);
                res.add(cur);
            }
        }
        
        //loop the array
        for(int i = 0; i < nums.length; i++)
        {
            if(i + 1 < nums.length)
            {
                if(nums[i + 1] - nums[i] == 1)
                {
                    continue;
                }
                else
                {
                    if(nums[i + 1] - nums[i] == 2)
                    {
                        String cur = "" + (nums[i] + 1);
                        res.add(cur);
                    }
                    else
                    {
                        String cur = "" + (nums[i] + 1) + "->" + (nums[i + 1] - 1);
                        res.add(cur);
                    }
                }
            }
            else
            {
                //last element
                if(nums[i] == upper)
                {
                    break;
                }
                else
                {
                    if(upper - nums[i] == 1)
                    {
                        String cur = "" + upper;
                        res.add(cur);
                    }
                    else
                    {
                        String cur = "" + (nums[i] + 1) + "->" + upper;
                        res.add(cur);   
                    }
                }
            }
        }
        
        return res;
    }
    

    }


Log in to reply
 

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