![[leetcode-523-Continuous Subarray Sum] [leetcode-523-Continuous Subarray Sum]](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
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.
Example 1:
Input: [23, 2, 4, 6, 7], k=6
Output: True
Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.
Example 2:
Input: [23, 2, 6, 4, 7], k=6
Output: True
Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.
Note:
- The length of the array won't exceed 10,000.
- You may assume the sum of all the numbers is in the range of a signed 32-bit integer.
思路:
首先想到用动态规划,使用dp[i][j]记录nums中i到j的和,然后随时判断是否满足余数为0.
注意处理k==0时候的情况。
但是直接用二维数组记录的话,提示内存不足,耗费空间。
更新公式为 dp[i][j] = dp[i][j-1]+nums[j] ,可以看出dp[i][j]只与上一个dp[i][j-1]有关,
于是用两个变量替代即可。得到如下代码,时间复杂度为O(n2).
bool checkSubarraySum(vector<int>& nums, int k)
{
int len = nums.size();
// vector<vector<int>> dp(len, vector<int>(len, 0));
long long cur = , pre = ;
for (int i = ; i < len;i++)
{
for (int j = i; j < len;j++)
{
if (j == i)cur = nums[i];
else
{
cur = pre + nums[j];
if (k != && cur % k == )return true;
else if (k == && cur == ) return true;
}
pre = cur;
}
}
return false;
}
后来参考网上大牛的代码,学习到了他们的解法。
比如他们用一个set去存储i之前元素和的余数,如果往后遍历到j元素和的余数之前出现过,说明i到j的和为k的整数倍。
这样时间复杂度为O(n).
class Solution {
public:
bool checkSubarraySum(vector<int>& nums, int k) {
int n = nums.size(), sum = , pre = ;
unordered_set<int> modk;
for (int i = ; i < n; ++i) {
sum += nums[i];
int mod = k == ? sum : sum % k;
if (modk.count(mod)) return true;
modk.insert(pre);
pre = mod;
}
return false;
}
};
参考:
https://discuss.leetcode.com/topic/80892/concise-c-solution-use-set-instead-of-map