Easy to understand Java O(N) solution


  • 0
    S
    public class Solution {
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            List<String> result=new ArrayList<String>();
            StringBuilder sb=new StringBuilder();
            //use long to avoid integer overflow
            long low, high;
            for(int i=0;i<=nums.length;i++){
                //i==0: interval=nums[0]-lower
                low=(i==0)?lower-1:nums[i-1];
                //i=N: interval=upper-nums[N]
                high=(i==nums.length)?upper+1:nums[i];
                if(high-low>1) sb.append(low+1);
                if(high-low>2){
                  sb.append("->");
                  sb.append(high-1);
                }
                if(sb.length()>0){
                    result.add(sb.toString());
                    sb=new StringBuilder();
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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