228. Summary Ranges
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”].
grandyang: http://www.cnblogs.com/grandyang/p/4603555.html
方法1:
思路:
用 j 来记录interval的长度,区别对待区间长度为1 和>1的输出。
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
if (nums.size() == 0) return result;
int i = 0, n = nums.size();
while (i < n){
int j = 1;
while ( i + j < n && nums[i + j] == nums [i] + j){
j++;
}
if (j == 1) {
// 单个数字
result.push_back(to_string(nums[i]));
}
else {
// 区间
result.push_back(to_string(nums[i]) + "->" + to_string(nums[i + j - 1]));
}
i += j;
}
return result;
}
};
方法2: two pointers
思路:
用双指针分别标记begin和end,每次发现一个区间就推入。这里有个follow-up是如果有重复数字怎么办?只需要多加comment里一个||的判断条件就好了:和下一个数字重复无条件前进。
易错点
- end的heap-overflow
- begin每次移动之后要跟上
- for loop的话就有个trick:每次跳跃可以把begin = -1, 并加入判断语句归并begin and end(见第二种)
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
int begin = 0, end = begin;
int n = nums.size();
while (end < nums.size()){
if (end < n - 1 && nums[end] + 1 == nums[end + 1]){
// if (end < n - 1 && (nums[end] + 1 == nums[end + 1] || nums[end] == nums[end + 1])){
end++;
}
else {
if (begin == end){
result.push_back(to_string(nums[begin]));
}
else {
result.push_back(to_string(nums[begin]) + "->" + to_string(nums[end]));
}
end++;
begin = end;
}
}
return result;
}
};
标记begin跳loop。
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
int begin = -1, end = begin;
int n = nums.size();
for (int i = 0; i < n; i++){
if (begin == -1) {
begin = i;
end = i;
}
if (end < n - 1 && nums[end] + 1 == nums[end + 1] ){
end++;
}
else {
if (begin == end){
result.push_back(to_string(nums[begin]));
}
else {
result.push_back(to_string(nums[begin]) + "->" + to_string(nums[end]));
}
begin = -1;
}
}
return result;
}
};