163. Missing Ranges

2389 단어
// Line 18: error: bad operand types for binary operator '-'
class Solution {
    public List findMissingRanges(int[] nums, int lower, int upper) {
        List res = new ArrayList();
        if (nums == null) {
            String range = lower + "->" + upper;
            res.add(range);
        }
        int i = 0;
        while (i < nums.length && lower <= upper) {
            int temp = nums[i];
            if (temp == lower) {
                lower++;
            } else if (temp > lower) {
                if (temp - lower == 1) {
                    res.add("" + lower);
                    lower = temp + 1;
                } else {
                    res.add(lower + "->" + temp - 1); // error
                    lower = temp + 1;
                }
            }
        }
        
        if (lower <= upper) {
            if (lower == upper) {
                res.add("" + lower);
            } else {
                res.add(lower + "->" + upper);
            }
        }
        
        return res;
    }
}
// error, Run Code Status: Time Limit Exceeded
// forget to increment i in the while loop
class Solution {
    public List findMissingRanges(int[] nums, int lower, int upper) {
        List res = new ArrayList();
        if (nums == null) {
            String range = lower + "->" + upper;
            res.add(range);
        }
        int i = 0;
        while (i < nums.length && lower <= upper) {
            int temp = nums[i];
            if (temp == lower) {
                lower++;
            } else if (temp > lower) {
                if (temp - lower == 1) {
                    res.add("" + lower);
                    lower = temp + 1;
                } else {
                    res.add(lower + "->" + (temp - 1));
                    lower = temp + 1;
                }
            }
            i++;
        }
        
        if (lower <= upper) {
            if (lower == upper) {
                res.add("" + lower);
            } else {
                res.add(lower + "->" + upper);
            }
        }
        
        return res;
    }
}

좋은 웹페이지 즐겨찾기