# LeetCode Summary Ranges

LeetCode 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"].`

```class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ans;
int n = nums.size(), i = 0, j = 1;
if (n == 0)return ans;
while (j < n) {
if (nums[j] - nums[j - 1] == 1) ++j;
else {
if (j - i == 1)ans.push_back(to_string(nums[i]));
else ans.push_back(to_string(nums[i]) + "->" + to_string(nums[j - 1]));
i = j++;
}
}
if (j - i == 1)ans.push_back(to_string(nums[i]));
else ans.push_back(to_string(nums[i]) + "->" + to_string(nums[j - 1]));
return ans;
}
};
```

```class Solution {
private:
struct Range {
int start, end;
Range(int s, int e) :start(s), end(e) {};
};
void add2Ans(int a, int b, vector<Range>& ranges) {
if (ranges.empty() || ranges[ranges.size() - 1].end != a - 1) {
ranges.push_back(Range(a, b));
}
else {
ranges[ranges.size() - 1].end = b;
}
}
void helper(vector<int>& nums, int start, int end, vector<Range>& ranges) {
if (start == end || end - start == nums[end] - nums[start]) {
return;
}
int mid = start + (end - start) / 2;
helper(nums, start, mid, ranges); // 先左区间
helper(nums, mid + 1, end, ranges); // 后右区间
}

public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ans;
if (nums.empty())return ans;
vector<Range> ranges;
helper(nums, 0, nums.size() - 1, ranges);
for (const auto& r : ranges) {
if (r.start == r.end)ans.push_back(to_string(r.start));
else ans.push_back(to_string(r.start) + "->" + to_string(r.end));
}
return ans;
}
};
```

```class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ans;
if (nums.empty())return ans;
int i = 0, j = 1, n = nums.size();
while (j < n) {
while (j < n && (nums[j] == nums[j - 1] || nums[j] - nums[j - 1] == 1))++j; // 考虑重复元素
if (j >= n)break;
if (j - 1 == i)ans.push_back(to_string(nums[i]));
else ans.push_back(to_string(nums[i]) + "->" + to_string(nums[j - 1]));
i = j++;
}
if (j - 1 == i)ans.push_back(to_string(nums[i]));
else ans.push_back(to_string(nums[i]) + "->" + to_string(nums[j - 1]));
return ans;
}
};
```