523. Continuous Subarray Sum
https://leetcode.com/problems/continuous-subarray-sum/description/
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.
Thoughts
是否存在和是K的倍数且长度大于1的子数组。subarray sum => presum,DP或窗口。当presum出现相同余数时,说明中间子数组的和为K的倍数,因为a[i]+a[i+1]+...+a[j]=n1K+q; a[i]+a[i+1]+...+a[j]+...+a[n]=n2K+q => a[j+1]+...+a[n]=(n2−n1)K。因此用presum记录sum%K的最早出现的位置。并且添加默认(0, -1)进presum来处理结果刚好是前缀的情况。
Last updated
Was this helpful?