leetcode 523. Continuous Subarray Sum
程序员文章站
2022-04-25 09:54:43
...
这个题目自己刚开始以为用暴力求解是最简单的方法,最优方法是动态规划,没想到还有这种解法,又好理解又快。
基本思路是这样:
class Solution {
public:
bool checkSubarraySum(vector<int>& nums, int k) {
int length=nums.size();
if(length<2)
return false;
if(k==0)
{
for(int i=1;i<length;i++)
{
if(nums[i]==0 && nums[i-1]==0)
return true;
else
return false;
}
return false;
}else{
set<int> s;
long sum=0;
for(int i=0;i<length;i++)
{
sum=sum+nums[i];
if(sum%k==0 && i!=0)
return true;
else if(sum%k!=0 && s.find(sum%k)!=s.end())
return true;
else
{
s.insert(sum%k);
}
}
return false;
}
}
};
上一篇: 开机提示EM DISK错误的解决
下一篇: 诸葛亮去世前除掉两个人,为蜀汉铺好了后路
推荐阅读
-
LeetCode 560 Subarray Sum Equals K (hash)
-
Leetcode0523--Continuous Subarray Sum 连续和倍数
-
LeetCode-209-Minimum Size Subarray Sum
-
LeetCode题解——862.Shortest Subarray with Sum at Least K
-
(M)Dynamic Programming:523. Continuous Subarray Sum
-
leetcode 523. Continuous Subarray Sum
-
Continuous Subarray Sum
-
523. Continuous Subarray Sum
-
Leetcode 523.Continuous Subarray Sum
-
LeetCode 523. Continuous Subarray sum和 525. Contiguous Array和560. Subarray Sum Equals K