Question
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
Traverse array, remember not to forget the last element.
public class Solution {
public List<String> summaryRanges(int[] nums) {
int length = nums.length;
List<String> result = new ArrayList<String>();
if (length == 0)
return result;
StringBuffer tmp = new StringBuffer();
int startNum = nums[0];
int endNum = nums[0];
if (length == 1) {
tmp.append(startNum);
result.add(tmp.toString());
return result;
}
for (int i = 0; i < length - 1; i++) {
if (nums[i] != nums[i + 1] - 1) {
tmp = new StringBuffer();
endNum = nums[i];
if (startNum == endNum) {
tmp.append(startNum);
} else {
tmp.append(startNum);
tmp.append("->");
tmp.append(endNum);
}
result.add(tmp.toString());
startNum = nums[i + 1];
}
}
tmp = new StringBuffer();
endNum = nums[length - 1];
if (startNum == endNum) {
tmp.append(startNum);
} else {
tmp.append(startNum);
tmp.append("->");
tmp.append(endNum);
}
result.add(tmp.toString());
return result;
}
}