Easy understand Java solution with comments


  • 0
    W
    public static List<String> summaryRanges(int[] nums) {
    	List<String> result = new ArrayList<>();
    	if (nums == null || nums.length == 0)
    		return result;
    
    	int first = nums[0], last = nums[0];
    	for (int i = 1; i < nums.length; i++) {
    		if (nums[i - 1] + 1 == nums[i]) {
    			last = nums[i]; // 前后连续,所以更新last值
    		} else {
    			// 前后不连续,导致一段range产生
    			if (first != last) {
    				String range = "" + first + "->" + last;
    				result.add(range);
    			} else {
    				result.add("" + first);
    			}
    			// 加入上段range后,让first和last都指向当前数字
    			first = nums[i];
    			last = nums[i];
    		}
    	}
    	// 不要忘了加入最后一段range
    	if (first != last) {
    		String range = "" + first + "->" + last;
    		result.add(range);
    	} else {
    		result.add("" + first);
    	}
    	return result;
    }

Log in to reply
 

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