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.
似乎没怎么费工夫就完成了,要点应该是时间吧。。。
也就是说这道题是要遍历所有的连续子串的,用L表示The length of the array,那么一共有(L-1)*L/2个连续子串,计算每一个子串的和S,再判断是否有S能被k整除,就是目的了。
关键就在于计算的次数,利用空间换区时间,每次都将上一步的计算结果存储起来,即如果计算连续子串A[i,j]的和,可以用A[i,j] = A[i,j-1] + A[j]的式子得出结果,从A[0,1]开始计算A[0,1] = A[0] + A[1], 将结果保存,A[0,2] = A[0,1] + A[2],这样每一步求和计算所用到的加法次数为1。
若不使用额外空间保存则最坏情况的一次求和加法次数为L-1。
最后再将特殊情况加入,当k=0时,不可以使用求余%,那么只要判断数组内是否存在连续两个数为0就可以了,存在则return true,否则return false
代码:
bool checkSubarraySum(vector<int>& nums, int k) {
int s = nums.size();
if(k == 0){
for(int i = 0; i < s-1; ++i) {
if(nums[i] == 0 && nums[i+1] == 0){
return true;
}
}
return false;
}
int **a;
a = new int*[s];
for(int i = 0;i < s-1; ++i){
a[i] = new int[s];
for(int j = i+1; j < s; ++j){
if(j - i == 1){
a[i][j] = (nums[i] + nums[j]) % k;
}
else{
if(i == 0){
a[i][j] = (a[i][j-1] + nums[j]) % k;
}
else{
a[i][j] = (a[i-1][j] + k - nums[i]) % k;
}
}
if(a[i][j] == 0) {
return true;
}
}
}
return false;
}