leetcode 228:Summary Ranges
题目:
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指向终点。
代码:
import java.util.LinkedList;
import java.util.List;
public class SummaryRanges {
public static List<String> summaryRanges(int[] nums){
List<String> res=new LinkedList<String>();
int start=0,end=0;
int len=nums.length;
while(end<len){
if(end+1<len && nums[end+1]==nums[end]+1){
end++;
}else{
if(start==end){
res.add(Integer.toString(nums[start]));
}else{
String str=nums[start]+"->"+nums[end];
res.add(str);
}
++end;
start=end;
}
System.out.println("end:"+end);
}
return res;
}
public static void main(String[] args){
int[] nums={0,1,2,4,5,6,7};
List<String> result=summaryRanges(nums);
for(String i:result){
System.out.println("列表元素为:"+i);
}
}
}