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.
Show Similar Problems
Have you met this question in a real interview?
silu: Pay more attention to the corner case.
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> ret = new ArrayList<String>();
int len = nums.length;
if(len < 1)
return ret;
StringBuilder buffer = new StringBuilder();
for(int i = 0; i < nums.length; i++){
buffer.append(nums[i]);
if(i < len - 1 && nums[i] + 1 == nums[i + 1]){
buffer.append("->");
while(i < len - 1 && nums[i] + 1 == nums[i + 1]){
i++;
}
buffer.append(nums[i]);
}
ret.add(buffer.toString());
buffer = new StringBuilder();
}
return ret;
}
}