straightforward Java solution without overflow bug


  • 0
    A
    public class Solution {
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            List<String> list = new ArrayList<>();
            if (nums == null || nums.length == 0) {
                list.add((upper == lower) ? lower + "" : (lower + "->" + upper));
                return list;
            }
            if (nums[0] != lower) {
                list.add((nums[0] == lower + 1) ? lower + "" : lower + "->" +  (nums[0] - 1));
            }
            for(int i = 0; i < nums.length - 1; i++) {
                if (nums[i + 1] != nums[i] && nums[i + 1] > nums[i] + 1) {
                    list.add((nums[i + 1]  == 2 + nums[i]) ? (nums[i] + 1) + "" : (nums[i] + 1) + "->" +  (nums[i + 1] - 1));
                }
            }
            if (nums[nums.length - 1] != upper) {
                list.add((nums[nums.length - 1] == upper - 1) ? upper + "" : (nums[nums.length - 1] +  1) + "->" +  upper);
            }
            return list;
             
        }
    }

Log in to reply
 

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