summary ranges

Problem:

Given a sorted integer array without duplicates, return the summary of its ranges.

分析

给定一个排好序的数组,数组中不包含duplicates。比较简单的题目,遍历即可。注意处理各种corner case。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class  {
public List<String> summaryRanges(int[] nums) {
List<String> ret = new ArrayList<String>();
int length = nums.length;
if (length == 0) return ret;
if (length == 1) {
ret.add(nums[0] + "");
return ret;
}
for (int i = 0; i < length;i++) {
int base = nums[i];
while (i + 1 < length && (nums[i+1] - nums[i]) == 1) {
i++;
}
if (nums[i] != base) {
ret.add(base + "->" + nums[i]);
} else {
ret.add(base + "");
}
}
return ret;
}
}