Java AC


  • 0
    A
    public List<String> findMissingRanges(final int[] nums, final int lower, final int upper) {
            if (nums.length == 0) {
                return Arrays.asList(generateRange(lower, upper));
            }
    
            List<String> ranges = new ArrayList<>();
    
            if (nums[0] > lower) {
                ranges.add(generateRange(lower, nums[0]-1));
            }
    
            for (int i = 1; i < nums.length; i++) {
                long diff = (long)nums[i] - (long)nums[i-1];
                if (diff > 1) {
                    ranges.add(generateRange(nums[i-1]+1, nums[i]-1));
                }
            }
    
            if (nums[nums.length-1] < upper) {
                ranges.add(generateRange(nums[nums.length-1] + 1, upper));
            }
    
            return ranges;
        }
    
        private String generateRange(final int lower, final int upper) {
            if (lower == upper) {
                return "" + lower;
            } else {
                return "" + lower + "->" + upper;
            }
        }
    

Log in to reply
 

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