首页 > 代码库 > LeetCode:Continuous Subarray Sum
LeetCode:Continuous Subarray Sum
523. Continuous Subarray Sum Add to List
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.
1 2 3 4 5 6
1 3 6 10 15 21
思路:这里简单的记录一下当前子数组的和sum就可以了,注意一点当k是0的情况下的处理,如果k是0且数组中有连续的0,这种情况下也是可以的。
1 bool checkSubarraySum(vector<int>& nums, int k) 2 { 3 int size = nums.size(); 4 if (size == 0) 5 return false; 6 vector<int>sum(size, 0); 7 sum[0] = nums[0]; 8 for (int i = 1; i < size; i++) 9 sum[i] = sum[i - 1] + nums[i]; 10 for (int i = 0; i < size; i++) 11 for (int j = i + 1; j < size; j++) 12 if (k == 0 && (sum[j] - sum[i] + nums[i] ==0)|| 13 (k!=0&&(sum[j] - sum[i] + nums[i]) % k == 0)) 14 return true; 15 return false; 16 }
LeetCode:Continuous Subarray Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。