美文网首页
163. Missing Ranges

163. Missing Ranges

作者: 成江 | 来源:发表于2018-06-01 21:36 被阅读17次
    // Line 18: error: bad operand types for binary operator '-'
    class Solution {
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            List<String> res = new ArrayList<String>();
            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<String> findMissingRanges(int[] nums, int lower, int upper) {
            List<String> res = new ArrayList<String>();
            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;
        }
    }
    

    相关文章

      网友评论

          本文标题:163. Missing Ranges

          本文链接:https://www.haomeiwen.com/subject/ewnxsftx.html