Long but readable and easy to understand Java code


  • 0
    P

    '''class Solution {
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
    List<String> list = new ArrayList<>();
    if (nums == null || nums.length == 0) {
    if (lower == upper) {
    list.add(lower + "");
    } else {
    list.add(lower + "->" + upper);
    }
    return list;
    }

        String ans = checkLeftBound(lower, nums[0]);
        if (ans != "") {
            list.add(ans);
        }
        
        for (int i = 0; i < nums.length - 1; i++) {
            ans = getRange(nums[i], nums[i + 1]);
            if (ans != "") {
                list.add(ans);
            }
        }
        
        ans = checkRightBound(nums[nums.length - 1], upper);
        if (ans != "") {
            list.add(ans);
        }
        
        return list;
    }
    
    private String checkLeftBound(int a, int b) {
        if (a == b) {
            return "";
        }
        if (a + 1 == b) {
            return a + "";
        }
        return a + "->" + (b - 1);
    }
    
    private String getRange(int a, int b) {
        if (a == b || a + 1 == b) {
            return "";
        }
        if (a + 2 == b) {
            return (a + 1) + "";
        }
        return (a + 1) + "->" + (b - 1);
    }
    
    private String checkRightBound(int a, int b) {
        if (a == b) {
            return "";
        }
        if (a + 1 == b) {
            return b + "";
        }
        return (a + 1) + "->" + b;
    }
    

    }'''


Log in to reply
 

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