-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path228.summary-ranges.cpp
More file actions
40 lines (38 loc) · 917 Bytes
/
Copy path228.summary-ranges.cpp
File metadata and controls
40 lines (38 loc) · 917 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
* @lc app=leetcode id=228 lang=cpp
*
* [228] Summary Ranges
*/
// @lc code=start
#include "bits/stdc++.h"
using namespace std;
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
int n = nums.size();
// two pointers, [l, r)
int l = 0, r = 0;
while (r < n)
{
// find the range [l, r)
while (l == r || r < n && nums[r] == nums[r - 1] + 1)
{
++r;
}
// add the range to the result
if (l == r - 1)
{
result.push_back(to_string(nums[l]));
}
else
{
result.push_back(to_string(nums[l]) + "->" + to_string(nums[r - 1]));
}
// update the left pointer
l = r;
}
return result;
}
};
// @lc code=end