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"].
Code
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList<>();
if (nums == null || nums.length == 0) return result;
if (nums.length == 1) {
result.add(String.valueOf(nums[0]));
return result;
}
for (int i = 0; i < nums.length; i++) {
int a = nums[i];
while (i + 1 < nums.length && nums[i + 1] - nums[i] == 1) {
i++;
}
if (nums[i] == a) {
result.add(String.valueOf(a));
} else {
result.add(a + "->" + nums[i]);
}
}
return result;
}
}
Solution
很常规的思路,for循环中不断寻找符合条件的首数字和尾数字即可。
网友评论