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) {
LinkedList<String> list = new LinkedList<String>();
//若为null则返回null
if(nums==null){
return null;
}
//用来遍历的指针i
int i = 0;
int len = nums.length;
//StringBuffer用来存储字符串
StringBuffer sb = new StringBuffer();
while(i<len){
//连续数字起始位置
int begin = i;
while(i+1<len&&(nums[i+1]==nums[i]+1)){
i++;
}
//连续数字终止位置
int end = i++;
if(begin==end){
list.add(String.valueOf(nums[begin]));
}
else{
sb.append(nums[begin]);
sb.append("->");
sb.append(nums[end]);
list.add(sb.toString());
sb.delete(0, sb.length());
}
}
return list;
}
}
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"].