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"].
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
该题的意思是,返回范围连续的数。
我的做法是通过两个变量记录连续的区间,然后进行相应的输出即可。
我的代码如下
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> list=new ArrayList<>();
int a=0;
int b=0;
while(a<nums.length)
{
b=a;
while(((a+1)<nums.length) &&((nums[a]+1) ==nums[a+1])){
a++;
}
if(a==b){
String str=Integer.toString(nums[a]);
list.add(str);
}
if(a!=b){
String str=nums[b]+"->"+nums[a];
list.add(str);
}
a++;
}
return list;
}
}