Leetcode0523--Continuous Subarray Sum 连续和倍数
【转载请注明】https://www.cnblogs.com/igoslly/p/9341666.html
class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { int size = nums.size(); for(int i=0;i<size-1;i++){ int sum=nums[i]; for(int j=i+1;j<size;j++){ sum +=nums[j]; // 解决k=0 问题,判断是否整除 if(k==0 && sum==0) return true; if(k!=0 && sum%k==0) return true; } } return false; } };
class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { int sum=0; map<int,int> sumhash; for(int i=0;i<nums.size();i++){ sum+=nums[i]; // judge if k=0 if(k==0 && i<nums.size()-1){ if((nums[i]+nums[i+1])==0) return true; } // have previous sum%k if(k!=0 && sumhash.find(sum%k)!=sumhash.end()) return true; if(i!=0 && k!=0 && sum%k==0) return true; if(k!=0) sumhash[sum%k]++; } return false; } };
int t = (k == 0) ? sum : (sum % k); if (m.count(t)) { if (i - m[t] > 1) return true; } else m[t] = i;