Summary Ranges
Problem
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"]
.
Solution
public class Solution {
public List<String> summaryRanges(int[] nums) {
if (nums == null || nums.length == 0) return new ArrayList<>();
List<String> res = new ArrayList<>();
int start = nums[0], end = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] - nums[i - 1] == 1) end = nums[i];
else {
res.add(start == end ? start + "" : start + "->" + end);
start = end = nums[i];
}
}
res.add(start == end ? start + "" : start + "->" + end); //Do not forget the last range!
return res;
}
}
Analysis
The idea of this solution is similar to other Array Range problem, using start
and end
We init those two vars both with nums[0]
, then we loop through the given nums
If we find the contiguous range, we just update the end
Otherwise, we add the current range and set both start
and end
to current number
At the end, we add the last range cause we don't have a chance to compare them hence we didn't add them inside the loop