题目
Given a sorted integer array without duplicates,
return the summary of its ranges.
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
给一个有序数组,将数组中连续的数字的变成range的形式
分析
这道题居然是medium难度的让我大跌眼镜。一遍扫描就可以了,具体看代码
代码
public List<String> summaryRanges(int[] nums) {
List<String> list = new ArrayList<>();
if(nums == null || nums.length == 0) return list;
int start = nums[0];
int prev = nums[0];
int cur = nums[0];
for(int i = 1; i < nums.length; i ++){
cur = nums[i];
if(cur != prev + 1){ //不连续
String info = start == prev ? "" + start : start + "->" + prev;
list.add(info);
start = cur;
}
prev = cur;
}
list.add(start == prev ? "" + start : start + "->" + prev);
return list;
}
网友评论