Java Solution


  • 0
    A
    class Solution {
    	public List<String> findMissingRanges( int[] nums, int lower, int upper ) {
    		if (nums == null || nums.length == 0)
    			return Arrays.asList( toStr( lower, upper ) );
    		else if (nums.length == 1)
    			if (lower == upper)
    				return Arrays.asList();
    			else if (nums[0] == lower)
    				return Arrays.asList( toStr( lower + 1, upper ) );
    			else if (nums[0] == upper)
    				return Arrays.asList( toStr( lower, upper - 1 ) );
    			else
    				return Arrays.asList( toStr( lower, nums[0] - 1 ), toStr( nums[0] + 1, upper ) );
    
    		int l = 0;
    		List<String> out = new ArrayList<>();
    
    		if (nums[l] != lower)
    			out.add( toStr( lower, nums[l++] - 1 ) );
    		for (l = 0; l < nums.length - 1; l++)
    			if ( nums[l] == nums[l+1])
    				continue;
    			else if (nums[l] + 1 != nums[l + 1])
    				out.add( toStr( nums[l] + 1, nums[l + 1] - 1 ) );
    		if (nums[l] < upper)
    			out.add( toStr( nums[l] + 1, upper ) );
    		return out;
    	}
    
    	private static String toStr( int a, int b ) {
    		return a == b ? String.valueOf( a ) : a + "->" + b;
    	}
    }
    

Log in to reply
 

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