A not-so-concise Java solution with good readability


  • 1
    H

    Not the best concise code but very easy to read and write without bug.

    public class Solution { 
    public List<String> findMissingRanges(int[] nums, int lower, int upper) { 
        List<String> result = new ArrayList<String>(); 
        // null check
        if (null == nums || lower > upper) { 
            return result; 
        }
        // empty case
        if (0 == nums.length) {
            if (lower == upper) {
                result.add(String.valueOf(lower));
            } else {
                result.add(lower + "->" + upper);
            }
            return result;
        }
        // if lower is not in nums[]
        if (nums[0] != lower) {
            if (nums[0] == lower + 1) {
                result.add(String.valueOf(lower));
            } else {
                result.add(lower + "->" + (nums[0] - 1));
            }
        }
        // general case assuming nums[0] and nums[tail] are two boundaries
        for (int i = 0; i < nums.length - 1; i++) {
            if (2 == nums[i + 1] - nums[i]) {
                result.add(String.valueOf(nums[i] + 1));
            }
            if (nums[i + 1] - nums[i] > 2) {
                result.add(String.valueOf((nums[i] + 1) + "->" + (nums[i + 1] - 1)));
            }
        }
        // if upper is not in nums[]
        int tail = nums[nums.length - 1];
        if (tail != upper) {
            if (tail == upper - 1) {
                result.add(String.valueOf(upper));
            } else {
                result.add((tail + 1) + "->" + upper);
            }
        }
        return result; 
    }

  • 0
    3

    it's very readable, but there's some minors in your code

    if (nums[0] != lower)

    i think what you want to express is "if(lower <= nums[0])"
    with the same idea:

    if (tail != upper)

    i think it should be "if(upper >= tail)"


Log in to reply
 

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