My Simple AC java solution


  • 1
    Z
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        ArrayList<String> res = new ArrayList<String>();
        if (nums == null || nums.length == 0) {
            makeRange(res, lower, upper);
            return res;
        }
    	if (nums[0] != lower) {
    		makeRange(res, lower, nums[0] - 1);
    	}
    	for (int i = 1; i < nums.length; i++) {
    		if (nums[i] != nums[i - 1] + 1) {
    			makeRange(res, nums[i - 1] + 1, Math.min(nums[i] - 1, upper));
    		}
    	}
    	if (nums[nums.length - 1] != upper) {
    		makeRange(res, Math.min(upper, nums[nums.length - 1] + 1), upper);
    	}
    	return res;
    }
    
    public void makeRange(ArrayList<String> res, int start, int end) {
    	if (start == end) {
    		res.add(start + "");
    	} else {
    		StringBuilder sb = new StringBuilder();
    		sb.append(start).append("->").append(end);
    		res.add(sb.toString());
    	}
    }

Log in to reply
 

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