题目
给定一个无重复元素的有序整数数组,返回数组区间范围的汇总。
示例 1:
输入: [0,1,2,4,5,7]
输出: ["0->2","4->5","7"]
解释: 0,1,2 可组成一个连续的区间; 4,5 可组成一个连续的区间。
示例 2:
输入: [0,2,3,4,6,8,9]
输出: ["0","2->4","6","8->9"]
解释: 2,3,4 可组成一个连续的区间; 8,9 可组成一个连续的区间。
C++解法
#include <iostream>
#include <vector>
#include <map>
#include <set>
using namespace std;
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ranges;
if (nums.empty()) return ranges;
if (nums.size() == 1) {
ranges.push_back(to_string(nums[0]));
return ranges;
}
long lower = -1;
long delta = 0;
long upper = -1;
for (int i = 0; i < nums.size() - 1; i++) {
if (lower == -1) {
lower = nums[i];
upper = nums[i];
}
delta = (long)nums[i+1] - (long)nums[i];
if (delta == 1) { upper = nums[i + 1]; }
if (delta != 1 || i == nums.size() - 2) {
if (lower == upper) {
ranges.push_back(to_string(lower));
} else {
ranges.push_back(to_string(lower) + "->" + to_string(upper));
}
if (upper != nums[i + 1] && i == nums.size() - 2) ranges.push_back(to_string(nums[i + 1]));
lower = -1;
upper = -1;
}
}
return ranges;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
Solution solution;
vector<int> vec {0,1,2,4,5,7};
auto ranges = solution.summaryRanges(vec);
for (auto range: ranges) {
cout << range << endl;
}
vec = {0, 2, 3, 4, 6, 8, 9};
ranges = solution.summaryRanges(vec);
for (auto range: ranges) {
cout << range << endl;
}
vec = {-2147483648,-2147483647,2147483647};
ranges = solution.summaryRanges(vec);
for (auto range: ranges) {
cout << range << endl;
}
return 0;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/summary-ranges