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