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.
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> ret = new ArrayList<String>();
if (nums == null || nums.length == 0)
return ret;
int i = 0;
int flag = 0;
while (i < nums.length) {
StringBuilder sb = new StringBuilder();
sb.append(nums[i]);
while (i + 1 < nums.length && nums[i] + 1 == nums[i + 1]) {
flag = 1;
i++;
}
if (flag == 1) {
sb.append("->");
sb.append(nums[i]);
}
ret.add(sb.toString());
i++;
flag = 0;
}
return ret;
}
}