题目链接这里
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> result=new LinkedList<String>();
if(nums==null)
{
return result;
}
StringBuilder sb=new StringBuilder();
boolean continueFlag=false;
int continueCount=0;
for(int i=0;i<nums.length;i++)
{
if(continueFlag)
{
if(nums[i]-1!=nums[i-1])
{
if(continueCount==1)
{
result.add(sb.toString());
}
else
{
sb.append("->"+nums[i-1]);
result.add(sb.toString());
}
continueFlag=false;
i--;
continueCount=0;
sb=new StringBuilder();
}
else
{
continueCount++;
}
}
else
{
continueFlag=true;
sb.append(nums[i]);
continueCount++;
}
}
if(continueCount!=0)
{
if(continueCount==1)
{
result.add(sb.toString());
}
else
{
sb.append("->"+nums[nums.length-1]);
result.add(sb.toString());
}
}
return result;
}
}
别人的牛逼算法。可以避免检测边界
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<String>();
if(nums == null || nums.length == 0)
return res;
int start = 0;
int end = 0;
while(end < nums.length){
StringBuilder sb = new StringBuilder();
while(end < nums.length - 1 && nums[end] == nums[end + 1] - 1){
end ++;
}
if(start == end){
sb.append(nums[start]);
res.add(sb.toString());
}else{
sb.append(nums[start]);
sb.append("->");
sb.append(nums[end]);
res.add(sb.toString());
}
end++;
start = end;
}
return res;
}