Continuous Subarray Sum
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等于0,这里要注意k=0的情况。暴力求解不美观,我们需要一点技巧来重新求解这道题。当a和b除以c的余数相同时,那么(a-b)就一定可以整除c,这个结论很好证明,在此就不再赘述。首先我们可以生成一个新字典,key是余数,value是位置,再新建一个变量保存累加和。通过遍历一次数组,不断地累加元素,当k不等于0时就把累加和(total)除以k的余数存进字典,如果k=0,就直接存total。存之前判断字典中是否已经存在该余数,如果存在,那么就可以返回True,如果不存在,就按照以上步骤存进字典。代码如下:
class Solution(object): def checkSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ cursum = dict() cursum[0] = -1 total = 0 for i in range(len(nums)): total += nums[i] if k != 0: total %= k if total in cursum: if (i-cursum.get(total)) > 1: return True else: cursum[total] = i return False