Simpe Java Solution


  • 0
    K
    public List<String> summaryRanges(int[] nums) {
        
        int len = nums.length;
     
        List<String> result = new ArrayList<String>();
    
    	int step = 1;
    
    	for(int i=0; i< len; ){
    
    		int temp = nums[i];
    		
    		StringBuilder tmpStr = new StringBuilder();
    		
    		tmpStr.append(nums[i]+"->");
    
    		while(++i< len && nums[i-1] +1 == nums[i]){
    
    		}
    
    		if(temp == nums[i-1]){
    			result.add(temp+"");
    		}else {
    			result.add(tmpStr.append(nums[i - 1]).toString());
    		}
    	}
    
    	return  result;
        
    }

  • 0
    D

    public List<String> summaryRanges(int[] nums) {

        List<String> list = new ArrayList<String>();
        if(nums.length < 1) {
            return list;
        }
        
        if(nums.length < 2) {
            list.add(nums[0]+"");
            return list;
        }
        
        int x = 0;
    
        for(int index = 0; index < nums.length; index++) {
            if(index > 0) {
                if((nums[index] - nums[index-1]) != 1) {
                    if(x > 1) {
                        list.add(createRange(nums, index - x, index - 1).toString());
                    }else {
                        list.add(nums[index-1]+"");
                    }
                    if(index + 1 == nums.length) {
                        list.add(nums[index]+"");
                    }
                    x = 0;
                }else {
                    if(index + 1 == nums.length) {
                        list.add(createRange(nums, index - x, index).toString());
                    }
                } 
            }
            x++;
        }
        
        return list;
        
    }
    
    private StringBuilder createRange(int[] nums, int x, int j) {
        StringBuilder s = new StringBuilder();
        s.append(nums[x]);
        s.append("->");
        s.append(nums[j]);
        return s;
    }

Log in to reply
 

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