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"].
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> list = new ArrayList<String>();
if (nums == null || nums.length == 0) {
return list;
}
int start = nums[0];
int pre = nums[0];
for (int i = 1; i <= nums.length; i++) {
int n = nums[0] - 1;
if (i != nums.length) {
n = nums[i];
}
if (n == pre + 1) {
pre++;
} else {
StringBuilder sb = new StringBuilder();
sb.append(start);
if (start != pre) {
sb.append("->").append(pre);
}
list.add(sb.toString());
start = n;
pre = n;
}
}
return list;
}
}
没有评论:
发表评论