-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode-228-SummaryRanges.cpp
63 lines (56 loc) · 1.41 KB
/
leetcode-228-SummaryRanges.cpp
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#include <unordered_map>
class Solution {
public:
std::vector<std::string> summaryRanges(std::vector<int>& nums) {
std::vector<std::string> res;
int start = 0,
end = 0;
if(!nums.empty())
{
start = nums[0];
end = nums[0];
}
for(size_t i = 0; i<nums.size(); ++i)
{
if((i<(nums.size()-1) && nums[i+1] != (end+1)) || (i==nums.size()-1))
{
std::string temp = std::to_string(start);
if(start != end)
{
temp += "->" + std::to_string(end);
}
res.emplace_back(temp);
if(i<(nums.size()-1))
{
start = nums[i+1];
} else {
break;
}
}
if(i<(nums.size()-1))
{
end = nums[i+1];
}
}
return res;
}
};
int main(){
std::vector<int> nums = {0,1,2,4,5,7};
auto res = Solution().summaryRanges(nums);
std::cout << "[";
for(size_t i = 0; i<res.size(); ++i)
{
std::cout << "\"" <<res[i] << "\"" ;
if(i<(res.size()-1))
{
std::cout << "," ;
}
}
std::cout << "]" << std::endl;
return EXIT_SUCCESS;
}