LeetCode
来源:互联网 发布:中电数据官网 编辑:程序博客网 时间:2024/06/05 21:04
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=6Output: TrueExplanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.
Example 2:
Input: [23, 2, 6, 4, 7], k=6Output: TrueExplanation: 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; }};
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Android--TabActivity-Fragment学习
- 《算法导论》二叉查找树的实现
- 使用Python MrJob的MapReduce实现电影推荐系统
- Zynq-Linux移植学习笔记之12-gpio驱动配置
- 动态规划—03采药
- LeetCode
- 通过考试(京东2017实习生真题)
- KNN(K近邻)算法的简单入门
- eclipse中的信息等价转换插件
- C语言文件操作函数
- Oracle PL/SQL开发基础(第十一弹:表集合操作)
- 二分法查找的条件设置
- MySQL数据库简介
- Nginx介绍及启动