原题链接在这里:https://leetcode.com/problems/summary-ranges/
题目:
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7]
, return ["0->2","4->5","7"].
题解:
s 是start index, e是end index. 看后一个数是否是前一个数加一,是就移动e, 不是就要加结果。加结果时分类讨论, s==e 和 s!=e加法不同。
Time Complexity: O(nums.length). Space: O(n), n是res的大小。
AC Java:
1 class Solution { 2 public List<String> summaryRanges(int[] nums) { 3 List<String> res = new ArrayList<String>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 7 8 int s = 0; 9 int e = 0; 10 while(e < nums.length){ //error 11 if(e< nums.length-1 && nums[e]+1 == nums[e+1]){ 12 e++; 13 }else{ 14 if(s == e){ 15 res.add(String.valueOf(nums[s])); 16 }else{ 17 res.add(String.valueOf(nums[s]) + "->" + String.valueOf(nums[e])); 18 } 19 20 e++; 21 s = e; 22 } 23 } 24 25 return res; 26 } 27 }