-
Notifications
You must be signed in to change notification settings - Fork 8
/
solution.cpp
87 lines (83 loc) · 2.31 KB
/
solution.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* 28 / 28 test cases passed.
* Status: Accepted
* Runtime: 4 ms
*/
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ans;
if (nums.size() == 0) return ans;
for (int i = 0; i < nums.size(); ++ i) {
int tmp = nums[i];
int j = i + 1;
for (; j < nums.size(); ++ j) {
if (nums[j] == tmp + 1) {
tmp = nums[j];
} else {
if (tmp == nums[i])
ans.push_back( to_string(nums[i]) );
else
ans.push_back( to_string(nums[i]) + "->" + to_string(tmp) );
j -= 1;
i = j;
break;
}
}
if (i == nums.size() - 1) {
ans.push_back( to_string(nums[i]) );
} else if (j == nums.size()) {
ans.push_back( to_string(nums[i]) + "->" + to_string(tmp) );
break;
}
}
return ans;
}
};
/**
* 28 / 28 test cases passed.
* Status: Accepted
* Runtime: 4 ms
*/
class Solution2 {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ans;
for (int i = 0; i < nums.size(); ) {
int low = i;
i += 1;
while (i < nums.size() && nums[i-1] + 1 == nums[i]) ++ i;
int high = i - 1;
string tmp = to_string( nums[low] );
if (low != high) {
tmp += "->" + to_string( nums[high] );
}
ans.push_back( tmp );
}
return ans;
}
};
/**
* 28 / 28 test cases passed.
* Status: Accepted
* Runtime: 0 ms
*/
class Solution3 {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ans;
if (nums.size() == 0) return ans;
int low = 0;
for (int high = 0; high < nums.size(); ++ high) {
if (high + 1 == nums.size() || nums[high] + 1 != nums[high + 1]) {
string tmp = to_string(nums[low]);
if (low != high) {
tmp += "->" + to_string(nums[high]);
}
ans.push_back(tmp);
low = high + 1;
}
}
return ans;
}
};