Java solution; not short; but elegant.


  • 0
    Z
    public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> ret = new ArrayList<>();
        
        if(nums == null || nums.length == 0)
            return ret; 
            
        Integer start = null;
        Integer end = null;
        
        for(int val : nums){
            if(start == null){ // uninitialized.
                end = start = val;
                continue;
            }
    
            if(end + 1 == val ){
                end ++;
            }
            else{
                ret.add(start == end ? ""+start: String.format("%d->%d", start,end));
                start = end = val; // reset;
            } 
        }
        
        // dont forget the last pair.
        if(start != null){
            ret.add(start == end ? ""+start: String.format("%d->%d", start,end));                
        }
        
        return ret; 
    }
    

    }


Log in to reply
 

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