Problem description:
/*
Given a sorted integer array without duplicates, return the summary of its ranges.

1
2
3
4
5
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.

1
2
3
4
5
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.

Solution:
A range covers consecutive elements. If two adjacent elements have difference larger than 11, the two elements does not belong to the same range.

To summarize the ranges, we need to know how to separate them. The array is sorted and without duplicates. In such array, two adjacent elements have difference either 1 or larger than 1. If the difference is 1, they should be put in the same range; otherwise, separate ranges.

We also need to know the start index of a range so that we can put it in the result list. Thus, we keep two indices, representing the two boundaries of current range. For each new element, we check if it extends the current range. If not, we put the current range into the list.

Don’t forget to put the last range into the list. One can do this by either a special condition in the loop or putting the last range in to the list after the loop.

Time complexity: O(n)
Space complexity: O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
if(nums.size() == 1){
res.push_back(to_string(nums[0]));
return res;
}
for(int i = 0; i< nums.size(); ++i){
int cur= nums[i];
while(i+1< nums.size() && (nums[i+1]- nums[i]== 1)){
i++;
}
if(cur != nums[i])
res.push_back(to_string(cur)+"->"+to_string(nums[i]));
else
res.push_back(to_string(nums[i]));
}

return res;
}
};