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"].
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<String>();
if (nums.length == 0) {
return res;
}
int start = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] - nums[i - 1] != 1) {
addString (nums[start], nums[i - 1], res);
start = i;
}
}
if (start == nums.length - 1) {
addString (nums[start], nums[start], res);
} else {
addString (nums[start], nums[nums.length - 1], res);
}
return res;
}
private void addString(int start, int end, List<String> list) {
String str = new String();
if (start == end){
str = start + "";
} else {
str = start + "->" + end;
}
list.add(str);
}
}