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 a 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.
找出数组中的连续子数组,而且子数组的长度至少是2,子数组的元素和要是k的倍数
思路:
k=0的情况,那么子数组元素和是0就是k的倍数
考虑元素和用积分数组,sum[j] - sum[i]就是i+1~j部分的和
子数组长度至少是2,所以i和j至少要间隔1
还有一个,如果a对k的余数和b对k的余数相等,那么(a-b)就能整除k
a = m1*k + n, b = m2 * k + n => a - b = (m1-m2) * k
遍历数组求和,每求一步和就保存它的前前一步的余数到set,如果现在对k的余数存在于set中,说明存在sum[ j ] - sum[ i] 能整除k,也就是i+1 ~ j部分的子数组的和能整除k
k=0的时候不能做除法,就直接保存sum
为什么需要一个pre呢? 因为题目中要求subarray中至少2个元素,
这就意味着积分数组中,sum[i] - sum[j] 时,i - j >=2,
那么加到第2个元素时,才能判断余数在不在set保存的左边界0,
同时保存加到第1个元素的sum对k的余数,
同理加到第3个元素时,只能看到sum到第1个元素的余数。
public boolean checkSubarraySum(int[] nums, int k) {
int n = nums.length;
int sum = 0;
int pre = 0;
HashSet<Integer> set = new HashSet<>();
for(int num : nums) {
sum += num;
int tmp = sum % k;
if(set.contains(tmp)) return true;
set.add(pre);
pre = tmp;
}
return false;
}
参考方法