首页 > 代码库 > 523

523

Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.

 

 1 class Solution {
 2 public:
 3     bool checkSubarraySum(vector<int>& nums, int k) {
 4         int n=nums.size(),pre=0,sum=0;
 5         unordered_set<int>mod_k;
 6         for(int i=0;i<n;i++)
 7         {
 8             sum+=nums[i];
 9             int mod=k==0?sum:sum%k;
10             if(mod_k.count(mod))
11                 return true;
12             mod_k.insert(pre);
13             pre=mod;
14         }
15         return false;
16     }
17 };

 

523