forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmissing-ranges.cpp
More file actions
28 lines (26 loc) · 763 Bytes
/
missing-ranges.cpp
File metadata and controls
28 lines (26 loc) · 763 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
// Time: O(n)
// Space: O(1)
class Solution {
public:
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
vector<string> ranges;
for (int i = 0, pre = lower - 1, cur = 0; i <= nums.size(); ++i, pre = cur) {
if (i == nums.size()) {
cur = upper + 1;
} else {
cur = nums[i];
}
if (cur - pre >= 2) {
ranges.emplace_back(getRange(pre + 1, cur - 1));
}
}
return ranges;
}
string getRange(const int lower, const int upper) {
if (lower == upper) {
return to_string(lower);
} else {
return to_string(lower) + "->" + to_string(upper);
}
}
};