题目描述:
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”].
这个题很简单,i指向range的开始,j指向range的末尾,记得加入String后i的指针要移动就行了。直接上代码:
public List<String> summaryRanges(int[] nums) {
List<String> result=new ArrayList<String>();
if(nums.length==0)
return result;
int i=0,j=1;
for(;j<nums.length;j++) {
if(nums[j]-nums[i]!=j-i){
if(j-i==1)
result.add(""+nums[i]);
else
result.add(nums[i]+"->"+nums[j-1]);
i=j;
}
}
if(j-i==1)
result.add(""+nums[j-1]);
else
result.add(nums[i]+"->"+nums[j-1]);
return result;
}