[抄题]:
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.
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
(a+(n*x))%x is same as (a%x)
For e.g. in case of the array [23,2,6,4,7] the running sum is [23,25,31,35,42] and the remainders are [5,1,1,5,0]. We got remainder 5 at index 0 and at index 3. That means, in between these two indexes we must have added a number which is multiple of the k. Hope this clarifies your doubt :)
[一句话思路]:
余数重复,必然增加了几倍
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- pos是之前的index,应该用i - pos是否>1来检测
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[算法思想:递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :

class Solution {
public boolean checkSubarraySum(int[] nums, int k) {
//cc
if (nums == null || nums.length == 0) return false;
//ini: map
Map<Integer, Integer> map = new HashMap<Integer, Integer>(){{put(0,-1);}};;
int total_sum = 0;
//for loop: get the same sum
for (int i = 0; i < nums.length; i++) {
total_sum += nums[i];
if (k != 0) total_sum %= k;
Integer pos = map.get(total_sum);
if (pos != null) {
if (i - pos > 1) return true;
}else {
map.put(total_sum, i);
}
}
return false;
}
}