-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsummary_ranges.cpp
More file actions
60 lines (54 loc) · 1.6 KB
/
summary_ranges.cpp
File metadata and controls
60 lines (54 loc) · 1.6 KB
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
/*
* =====================================================================================
*
* Filename: summary_ranges.cpp
*
* Description: 228. Summary Ranges
* https://leetcode.com/problems/summary-ranges/
*
* Version: 1.0
* Created: 10/07/2025 14:59:05
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <string>
#include <utility>
#include <vector>
#include "gtest/gtest.h"
class Solution {
public:
std::vector<std::string> summaryRanges(std::vector<int>& nums) {
if (nums.size() == 0) {
return {};
}
auto convert = [](const int a, const int b) -> std::string {
return a == b ? std::to_string(a) : (std::to_string(a) + "->" + std::to_string(b));
};
std::vector<std::string> ranges;
std::pair<int, int> last = {nums[0], nums[0]};
for (int val : nums) {
if (val == last.second + 1) {
last.second++;
} else if (val != last.second) {
ranges.push_back(convert(last.first, last.second));
last = {val, val};
}
}
ranges.push_back(convert(last.first, last.second));
return ranges;
}
};
TEST(Solution, summaryRanges) {
std::vector<std::pair<std::vector<int>, std::vector<std::string>>> cases = {
{{0, 1, 2, 4, 5, 7}, {"0->2", "4->5", "7"}},
{{0, 2, 3, 4, 6, 8, 9}, {"0", "2->4", "6", "8->9"}},
};
for (auto& [nums, ranges] : cases) {
EXPECT_EQ(Solution().summaryRanges(nums), ranges);
}
}