My Easy Java Solution


  • 0
    B
      public List<String> summaryRanges(int[] nums) {
    		List<String> result = new ArrayList<>();
    	       if (nums.length==0) {
    			return result;
    		}
    		int head = 0;
    		int tail = head;
    		int lastTail = head + 1;
    		for (; lastTail < nums.length; lastTail++) {
    			if (nums[lastTail] - nums[tail] == 1) {
    				tail=lastTail;
    				continue;
    			}
    			result.add(getRangeString(head, tail, nums));
    			head = tail = lastTail;
    		}
    		result.add(getRangeString(head, tail, nums));
    		return result;
    	}
    
    	private String getRangeString(int begin, int end, int[] nums) {
    		StringBuilder sb = new StringBuilder();
    		if (begin!=end) {
    			sb.append(String.valueOf(nums[begin])).append("->").append(nums[end]);
    		}else {
    			sb.append(nums[begin]);
    		}
    		
    		return sb.toString();
    	}

Log in to reply
 

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