问题:
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.
解决:
① 这道题给了我们一个数组和一个数字k,让我们求是否存在这样的一个连续的子数组,该子数组的数组之和可以整除k。
遍历所有的子数组,然后利用累加和来快速求和。在得到每个子数组之和时,我们先和k比较,如果相同直接返回true,否则再判断,若k不为0,且sum能整除k,同样返回true,最后遍历结束返回false。
class Solution {//78ms
public boolean checkSubarraySum(int[] nums, int k) {
for (int i = 0;i < nums.length;i ++){
int sum = nums[i];
for (int j = i + 1;j < nums.length;j ++){
sum += nums[j];
if (sum == k) return true;
if (k != 0 && sum % k == 0) return true;
}
}
return false;
}
}
② 若数字 a 和 b 分别除以数字 c,若得到的余数相同,那么(a - b)必定能够整除 c。
1、处理k为0的情况;2、用HashMap保存sum对k取余数,如果前序有余数也为sum % k的位置,那么就存在连续子数组和为k的倍数。
在discuss中看到的。。。。。。。。
class Solution { //13ms
public boolean checkSubarraySum(int[] nums, int k) {
// 23 2 4 6 7 ===> 23 % 6 ==> 5 % 6 ==> 5 + 2 ==> 7 % 6 ==> 1 + 4 ==> 5 % 6 ==> 5 + 6 ==> 5 % 6 ==> 12 % 6==> 0
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
map.put(0,-1);
int remainingSum = 0;
for(int i = 0 ; i < nums.length ; i ++){
remainingSum += nums[i];
if(k != 0)
remainingSum %= k;
if(map.containsKey(remainingSum)){
int pre = map.get(remainingSum);
if(i - pre > 1)
return true;
}else
map.put(remainingSum , i);
}
return false;
}
}