Summary Ranges 解答

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;
}
}
上一篇:collections系列


下一篇:7.在第4题中Hello.class所在路径下, 输入命令:java Hello.class,会出现什么结果,为什么?