LeetCode/solutions/228. Summary Ranges.md
2019-09-21 20:30:56 +08:00

30 lines
943 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [228. Summary Ranges](https://leetcode.com/problems/summary-ranges/)
# 思路
题意就是要求找出连续的区间。我们可以用start_i代表每个连续区间的开始下标
然后不断检查下一个数是不是连续的直到不连续为止然后就将这个区间的结果push进结果数组然后更新start_i处理下一个连续区间。
# C++
``` C++
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
if(nums.empty()) return vector<string>{};
int n = nums.size();
vector<string>res;
int start_i = 0, i = 0;
while(i < n){
while(i + 1 < n && nums[i] + 1 == nums[i + 1]) i++;
string out = to_string(nums[start_i]);
if(i != start_i)
out += ("->" + to_string(nums[i]));
res.push_back(out);
start_i = ++i;
}
return res;
}
};
```