diff --git a/cpp/2202/220228.cpp b/cpp/2202/220228.cpp new file mode 100644 index 0000000..c417498 --- /dev/null +++ b/cpp/2202/220228.cpp @@ -0,0 +1,47 @@ +#include +#include +#include + +typedef long long LL; + +/** + * 228. Summary Ranges + * You are given a sorted unique integer array nums. + * Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums. + * Each range [a,b] in the list should be output as: + * - "a->b" if a != b + * - "a" if a == b + */ + +class Solution { +public: + static std::vector summaryRanges(const std::vector& nums) { + if (nums.empty()) + return {}; + std::vector ret; + int prev = nums[0], intStart = nums[0]; + for (int i : nums) { + if (LL(i) - LL(prev) > 1) { + if (intStart == prev) + ret.push_back(std::to_string(intStart)); + else + ret.push_back(std::to_string(intStart) + "->" + std::to_string(prev)); + intStart = i; + } + prev = i; + } + if (intStart == nums.back()) + ret.push_back(std::to_string(intStart)); + else + ret.push_back(std::to_string(intStart) + "->" + std::to_string(nums.back())); + return ret; + } +}; + +int main() { + auto ret = Solution::summaryRanges({0,2,3,4,6,8,9}); + for (const auto& i : ret) { + std::cout << i << std::endl; + } + return 0; +} diff --git a/cpp/2202/CMakeLists.txt b/cpp/2202/CMakeLists.txt index 349725f..cbc0ae8 100644 --- a/cpp/2202/CMakeLists.txt +++ b/cpp/2202/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2202) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2202 220228-CN.cpp) +ADD_EXECUTABLE(2202 220228.cpp)