Java Solution Sharing


  • 0
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        if(nums == null || nums.length == 0) {
            if(lower == upper) return new ArrayList<>(Arrays.asList(Integer.toString(lower)));
            else return new ArrayList<>(Arrays.asList(Integer.toString(lower) + "->" + Integer.toString(upper))); 
        }
        
        int expected = lower;
        List<String> result = new ArrayList<>();
        for(int i=0; i<nums.length; i++) {
            if(nums[i] != expected) {
                if(nums[i] == expected + 1) result.add(Integer.toString(expected));
                else result.add(Integer.toString(expected) + "->" + Integer.toString(nums[i]-1));
            }
            expected = nums[i] + 1;
            if(i == nums.length-1 && nums[i] != upper) {
                if(upper == nums[i] + 1) result.add(Integer.toString(upper));
                else result.add(Integer.toString(expected) + "->" + Integer.toString(upper));
            }
        }
        return result;
    }

Log in to reply
 

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