leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
1590.cpp (639B)
0 class Solution { 1 public: 2 int minSubarray(const vector<int> &nums, int p) const { 3 const int n = size(nums); 4 5 int target = 0; 6 for (const int n : nums) 7 target = (target + n) % p; // avoid overflow 8 if (target == 0) return 0; 9 10 unordered_map<int, int> um; 11 int res = n, crnt = 0; 12 um[0] = -1; 13 14 for (int i = 0; i < n; i++) { 15 crnt = (crnt + nums[i]) % p; 16 17 const int goal = (crnt - target + p) % p; 18 if (um.count(goal)) res = min(res, i - um[goal]); 19 20 um[crnt] = i; 21 } 22 23 return res == n ? -1 : res; 24 } 25 };