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"].

public class Solution {
public List<String> summaryRanges(int[] nums) {
Range[] ranges = new Range[nums.length];
int size = 0;
for(int i=0; i<nums.length; i++) {
if (i > 0 && ranges[size-1].to + 1 == nums[i]) ranges[size-1].to ++;
else ranges[size++] = new Range(nums[i], nums[i]);
}
List<String> results = new ArrayList<String>();
for(int i=0; i<size; i++) {
else results.add(Integer.toString(ranges[i].from) + "->" + Integer.toString(ranges[i].to));
}
return results;
}
}
class Range {
int from, to;
Range(int from, int to) {
this.from = from;
this.to = to;
}
}

public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> ranges = new ArrayList<>();
if (nums == null || nums.length == 0) return ranges;
int[] range = new int[] {nums[0], nums[0]};
for(int i=1; i<=nums.length; i++) {
if (i<nums.length) {
if (range[1]+1 == nums[i]) {
range[1] = nums[i];
} else {
else ranges.add(Integer.toString(range[0]) + "->" + Integer.toString(range[1]));
range[0] = nums[i];
range[1] = nums[i];
}
} else {
else ranges.add(Integer.toString(range[0]) + "->" + Integer.toString(range[1]));
}
}
return ranges;
}
}