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"].
一刷
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<>();
if(nums == null || nums.length==0) return res;
int left = nums[0], next = left+1;
for(int i=1; i<nums.length; i++){
if(nums[i] == next) next++;
else{
res.add(getRange(left, next-1));
left = nums[i];
next = left+1;
}
}
res.add(getRange(left, next-1));
return res;
}
private String getRange(int a, int b){
if(a == b) return String.valueOf(a);
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append("->");
sb.append(b);
return sb.toString();
}
}