My accepted Java solution


  • 0
    A
    class Solution {
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            int next = lower;
            List<String> ans = new ArrayList<String>();
            StringBuilder sb = new StringBuilder();
            for(int i = 0;i < nums.length;i++){
                
                sb = new StringBuilder();
                if(nums[i] < next)
                    continue;
                if(next == nums[i]){
                    next++;
                    continue;
                }
                ans.add(getStr(next,nums[i] - 1));
                if(nums[i] == Integer.MAX_VALUE)
                    return ans;
                next = nums[i] + 1;
            }
            if(next == Integer.MIN_VALUE && nums.length > 0)
                return ans;
            if(next == upper)
                ans.add("" + next);
            if(next < upper)
                ans.add(getStr(next,upper));
            return ans;
        }
        
        String getStr(int n1,int n2){
            return n1 == n2?String.valueOf(n1):String.valueOf(n1) + "->" + String.valueOf(n2);
        }
    }
    

Log in to reply
 

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