Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:
Input: [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
题目:输入一个有序且无重复的整数数组,返回此数组中整数的连续取值范围。
实现思路:双指针找连续取值的起点和终点即可。题目输入的数组已经是排序且无重复的,所以end从start开始,只需要判断与nums[end+1] - nums[end]是否等于1即可,另外需要注意的是找到end后,start要移动到end+1的位置。
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> answer = new ArrayList<>();
int i = 0;
while (i < nums.length) {
StringBuilder sb = new StringBuilder();
sb.append(nums[i]);
int j = i;
while (++j < nums.length)
if (nums[j] - nums[j - 1] != 1)
break;
if (j > i + 1)
sb.append("->" + nums[j - 1]);
answer.add(sb.toString());
i = j;
}
return answer;
}
}