Easy Java solution consider overflow


  • 0
    P

    class Solution {
    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
    StringBuilder sb=new StringBuilder();
    List<String> sl=new ArrayList<String>();
    int current=lower;

        //travesal the array
        for(int i=0;i<nums.length;i++){
            
            if(current>nums[i])
                continue;
            //start only have two case, start==nums[0] or start< nums[0]
            if(current!=nums[i]){
                
            
             sb.setLength(0);
            sb.append(current);
    

    if(nums[i]-1>current){
    sb.append("->");
    sb.append(nums[i]-1);
    }
    sl.add(sb.toString());
    }
    if(nums[i]<=upper-1)
    current=nums[i]+1;
    else
    return sl;

    }
        
        
        //so current has not be count
        if(current<=upper){
            sb.setLength(0);
            sb.append(current);
            if(upper>current){
                sb.append("->");
                sb.append(upper);
            }
            sl.add(sb.toString());
        }
        
        return sl;
        
    }
    

    }


Log in to reply
 

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