题目:
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"].
在一个已经排好序的没有重复的数组中,现在要求其中连续的子序列,如上面给的例子那样。此题也有那么一点难度。我们可以看到主要是运用下标来表示,考虑用两个指针来指示,一个是start,另一个是end。如果发现,nums[end+1] == nums[end] + 1,那么就将这个end后移,一开始,end等于start。每次执行这个操作,也得分情况,如果某一个连续的数字成单的,那么直接存入这个list即可,否则end一直走,直到碰到第一个不连续的数字位置。
public static List<String> summaryRanges(int[] nums)
{
int length = nums.length;
List<String> list = new ArrayList<String>();
if(length == 0 || nums == null)
return list;
int i = 0;
int s = 0;
while(i < length)
{
if(i + 1 < length && nums[i+1] == nums[i] + 1)
{
i++;
}
else
{
if(s == i)
list.add(Integer.toString(nums[s]));
else
{
String str = nums[s] + "->" + nums[i];
list.add(str);
}
i = i + 1;
s = i;
}
}
return list;
}