forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 1
/
summary_ranges.cpp
58 lines (53 loc) · 1.59 KB
/
summary_ranges.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
/*
* Leet code problem - summary pages
* 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"].
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
std::vector<std::string> summaryRanges(std::vector<int>& nums) {
std::vector<std::string> ranges;
if (nums.empty()) {
return ranges;
}
std::string curr = std::to_string(nums[0]);
int range_start = nums[0];
for( size_t i = 1; i < nums.size(); ++i ) {
if (nums[i-1] + 1 == nums[i]) {
continue;
} else {
if ( range_start != nums[i-1]) {
curr += "->";
curr += std::to_string(nums[i-1]);
ranges.push_back(curr);
} else {
ranges.push_back(curr);
}
curr = std::to_string(nums[i]);
range_start = nums[i];
}
}
if (range_start != nums[nums.size() - 1]) {
curr += "->";
curr += std::to_string(nums[nums.size() - 1]);
}
ranges.push_back(curr);
return ranges;
}
void printVec( std::vector<std::string> ranges ) {
for ( size_t i = 0; i < ranges.size(); ++i ) {
if ( i != ranges.size() - 1 ) {
std::cout << ranges[i] << ", ";
} else {
std::cout << ranges[i] << std::endl;
}
}
}
int main() {
std::vector<int> nums{0,1,2,4,5,7};
std::vector<std::string> ranges = summaryRanges(nums);
printVec(ranges);
return 0;
}