diff --git a/cpp/2210/221026.cpp b/cpp/2210/221026.cpp new file mode 100644 index 0000000..4e573f4 --- /dev/null +++ b/cpp/2210/221026.cpp @@ -0,0 +1,39 @@ +#include +#include +#include + +/** + * 523. Continuous Subarray Sum + * + * Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise. + * An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k. + */ + +class Solution { +public: + static bool checkSubarraySum(const std::vector& nums, int k) { + int sum = nums[0] % k, n = nums.size(), prev = 0; + if (n < 2) + return false; + if (k == 1) + return true; + if (n == 2) + return (nums[0] + nums[1]) % k == 0; + std::unordered_set s{0, nums[0] % k}; + for (int i = 1; i < n; ++i) { + if (!(nums[i] % k) && !(nums[i - 1] % k)) + return true; + prev = sum; + sum = (sum + nums[i]) % k; + if (s.count(sum) && prev != sum) + return true; + s.insert(sum); + } + return false; + } +}; + +int main() { + std::cout << Solution::checkSubarraySum({1,2,12}, 6); + return 0; +} diff --git a/cpp/2210/CMakeLists.txt b/cpp/2210/CMakeLists.txt index a378f39..da71f7a 100644 --- a/cpp/2210/CMakeLists.txt +++ b/cpp/2210/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2210) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2210 221026-CN.cpp) +ADD_EXECUTABLE(2210 221026.cpp)