0228. Summary Ranges (E)
Summary Ranges (M)
题目
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.
题意
给定一个升序数组,将其中每一个相邻元素连续的子数组以区间字符串的形式表示,要求返回这样的区间字符串的汇总。
思路
用两指针分别指向符合条件的子数组的两端,按照题目要求进行处理。
代码实现
Java
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> ans = new ArrayList<>();
if (nums.length != 0) {
int start = nums[0];
int end = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1] + 1) {
// 扩大子数组长度
end++;
} else {
// 找到一个子数组,将其转化为区间字符串
String range = start == end ? start + "" : start + "->" + end;
ans.add(range);
start = nums[i];
end = nums[i];
}
}
// 还需要再进行一次处理
String range = start == end ? start + "" : start + "->" + end;
ans.add(range);
}
return ans;
}
}
JavaScript
/**
* @param {number[]} nums
* @return {string[]}
*/
var summaryRanges = function (nums) {
if (!nums.length) {
return []
}
let ans = []
let start = nums[0]
for (let i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1] + 1) {
ans.push(nums[i - 1] == start ? start + '' : start + '->' + nums[i - 1])
start = nums[i]
}
}
ans.push(nums[nums.length - 1] == start ? start + '' : start + '->' + nums[nums.length - 1])
return ans
}