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"].
Solution 1, Extend the original array to include last number twice, this is deal-breaker.
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<>();
if(nums == null || nums.length == 0) return res;
int[] extend = new int[nums.length+1];
for(int i=0; i< nums.length; i++){
extend[i] = nums[i];
}
extend[nums.length] = extend[nums.length-1];
int start = extend[0];
for(int i=1; i< extend.length; i++){
if(extend[i] != extend[i-1] +1){
int end = extend[i-1];
if(start == end){
res.add(Integer.toString(start));
}else{
res.add(start + "->" + end);
}
start = extend[i];
}
}
return res;
}
}
without extending, special check in the ending index
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<>();
if(nums == null || nums.length == 0) return res;
int start = nums[0];
for(int i=1; i<=nums.length; i++){
if(i == nums.length){
if(start == nums[nums.length-1]){
res.add(Integer.toString(start));
}else{
res.add(start + "->" + nums[nums.length-1]);
}
break;
}
if(nums[i] != nums[i-1] +1){
int end = nums[i-1];
if(start == end){
res.add(Integer.toString(start));
}else{
res.add(start + "->" + end);
}
start = nums[i];
}
}
return res;
}
}