Java Solution handling corner cases


  • 0
    M
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            List<String> list = new ArrayList<>();
            if (nums == null) return list;
            long lo = lower;
            for (int i = 0; i < nums.length; ++i) {
                if (i > 0 && nums[i] == nums[i - 1]) continue;
                int num = nums[i];
                if (num == lo) lo++;
                else {
                    if (num - 1 == lo) list.add(String.valueOf(lo));
                    else list.add(lo + "->" + (num - 1));
                    lo = (long)num + 1;
                }
            }
            if (upper >= lo) {
                if (upper == lo) list.add(String.valueOf(lo));
                else list.add(lo + "->" + upper);
            }
            return list;
        }
    

Log in to reply
 

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