O(n) time O(n) space
这道题纯考实现
因为字符串形式的数不方便pop_back所以最好用int来表示数,确认没问题了再把数转成字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public: vector<string> summaryRanges(vector<int>& nums) { vector<pair<int, int>> v; for (int x : nums) { if (v.empty() || v.back().second + 1 < x) { v.emplace_back(x, x); } else { v.back().second = x; } } vector<string> res; for (const auto &[b, e] : v) { if (b == e) { res.push_back(to_string(b)); } else { res.push_back(to_string(b) + "->" + to_string(e)); } } return res; } };
|
O(n) time O(1) space
[res.back(), prev, x]
- res.back() < prev ===> “res.back() -> prev”
- res.back() == prev ===> “res.back()”即一个孤立的数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: vector<string> summaryRanges(vector<int>& nums) { vector<string> res; int n = nums.size(); long prev = LONG_MIN; for (int i = 0; i <= n; ++i) { long x = i == n ? LONG_MAX : nums[i]; if (prev + 1 < x) { if (!res.empty() && stoi(res.back()) < prev) { res.back() += "->" + to_string(prev); } if (i < n) { res.push_back(to_string(x)); } } prev = x; } return res; } };
|