LeetCode - 523 - Continuous Subarray Sum
2017-04-18 22:31
453 查看
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:
Example 2:
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.
Subscribe to see which companies asked this question.
题意:给出一个数组和k值,求是否存在一个最长的子串和是k的倍数(子串长度大于1)
思路:唔,我实在不明白这题为啥划到dp里边了,想半天无从下手。网上大神给了一个o(n)的做法,统计前缀和%k,用map查询是否出现过这个值。出现过的话直接相减判断就好了,没出现过就丢进map里。服。
class Solution {
public:
bool checkSubarraySum(vector<int>& a, int k) {
map<int, int> m;
m.clear();
int sum = 0;
int len = a.size();
m[0] = -1;
for (int i = 0; i < len; i++) {
sum += a[i];
if (k) sum %= k;
if (m.find(sum) != m.end()) {
if (i - m[sum] > 1) return true;
}
else m[sum] = i;
}
return false;
}
};
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.
Subscribe to see which companies asked this question.
题意:给出一个数组和k值,求是否存在一个最长的子串和是k的倍数(子串长度大于1)
思路:唔,我实在不明白这题为啥划到dp里边了,想半天无从下手。网上大神给了一个o(n)的做法,统计前缀和%k,用map查询是否出现过这个值。出现过的话直接相减判断就好了,没出现过就丢进map里。服。
class Solution {
public:
bool checkSubarraySum(vector<int>& a, int k) {
map<int, int> m;
m.clear();
int sum = 0;
int len = a.size();
m[0] = -1;
for (int i = 0; i < len; i++) {
sum += a[i];
if (k) sum %= k;
if (m.find(sum) != m.end()) {
if (i - m[sum] > 1) return true;
}
else m[sum] = i;
}
return false;
}
};
相关文章推荐
- [leetcode523]Continuous Subarray Sum
- LeetCode: -Dynamic Programming-Continuous Subarray Sum[523]
- leetcode523 Continuous Subarray Sum
- 【LeetCode523】. Continuous Subarray Sum
- LeetCode 523 Continuous Subarray Sum (同余)
- LeetCode 523: Continuous Subarray Sum
- 523. Continuous Subarray Sum
- 523. Continuous Subarray Sum
- 523. Continuous Subarray Sum
- 523. Continuous Subarray Sum
- 523. Continuous Subarray Sum
- [LeetCode] Continuous Subarray Sum 连续的子数组之和
- Math-523-Continuous Subarray Sum
- 523. Continuous Subarray Sum
- 523. Continuous Subarray Sum
- [LeetCode] Continuous Subarray Sum
- 【leetCode523】Continuous Subarry Sum
- 523-Continuous Subarray Sum
- [LeetCode]Continuous Subarray Sum
- 523. Continuous Subarray Sum