leetcode523 Continuous Subarray Sum
思路:
令sum[p]表示p位置的前缀和。如果sum[i] % k == sum[j] % k (j - i > 1),则存在子段(i, j]的和能够整除k。
实现:
1 class Solution 2 { 3 public: 4 bool checkSubarraySum(vector<int>& nums, int k) 5 { 6 if (nums.size() < 2) return false; 7 int n = nums.size(); 8 for (int i = 0; i < n - 1; i++) 9 if (nums[i] == 0 && nums[i + 1] == 0) 10 return true; 11 if (k == 0) return false; 12 int sum = 0; 13 unordered_map<int, int> m; 14 m[0] = -1; 15 for (int i = 0; i < n; i++) 16 { 17 sum = (sum + nums[i]) % k; 18 if (m.count(sum)) 19 { 20 if (i - m[sum] > 1) 21 return true; 22 } 23 else m[sum] = i; 24 } 25 return false; 26 } 27 };
转载于:https://www.cnblogs.com/wangyiming/p/7445218.html
leetcode523 Continuous Subarray Sum相关推荐
- LintCode 402: Continuous Subarray Sum
LintCode 402: Continuous Subarray Sum 题目描述 给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大.输出答案时,请分别返回第一个数字和最后一个数字的下标 ...
- LeetCode 523. Continuous Subarray Sum
题目: Given a list of non-negative numbers and a target integer k, write a function to check if the ar ...
- LeetCode-Easy部分中标签为Dynamic Programming 523. Continuous Subarray Sum
原题 Given a list of non-negative numbers and a target integer k, write a function to check if the arr ...
- 523. Continuous Subarray Sum
class Solution { public:bool checkSubarraySum(vector<int>& nums, int k) {unordered_map< ...
- 【leetcode】523. Continuous Subarray Sum
题目如下: 解题思路:本题需要用到这么一个数学定理.对于任意三个整数a,b,k(k !=0),如果 a%k = b%k,那么(a-b)%k = 0.利用这个定理,我们可以对数组从头开始进行求和,同时利 ...
- leetcode 523. Continuous Subarray Sum | 523. 连续的子数组和(同余定理)
题目 https://leetcode.com/problems/continuous-subarray-sum/ 题解 没有想到 O(n) 的方法,于是直奔答案: 参考1:[宫水三叶]拓展到求方案数 ...
- LeetCode Subarray Sum Equals K
原题链接在这里:https://leetcode.com/problems/subarray-sum-equals-k/description/ 题目: Given an array of integ ...
- leetcode-581-Shortest Unsorted Continuous Subarray
题目描述: Given an integer array, you need to find one continuous subarray that if you only sort this su ...
- [LintCode] Minimum Size Subarray Sum 最小子数组和的大小
Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...
最新文章
- C++ 程序不一定从 main 处开始执行
- linux64平台上编译32位程序: GCC编译选项 -m64 -m32 -mx32
- jpa一级缓存和二级缓存_了解一级JPA缓存
- 【安卓开发 】Android初级开发(七)MD5加密
- 病毒周报(100301至100307)
- FFA 2021 专场解读 - 实时数据湖
- imp 只导表前10条数据_2020年玉石行情,从10条数据就能略窥一二
- 第三方魔兽金币交易平台的影响力会很快地褪去
- suse linux 忘记root密码,SUSE linux 忘记root密码
- 处理Cookie ( from http://edu.chinaz.com )
- cf两边黑屏怎么解决win10_win10开机黑屏时间长的解决方法教程
- Android R- CarAudioService之registerAudioPolicy动态注册(一)
- PyTorch深度学习(18)网络结构LeNet、AlexNet
- TIOBE 7 月编程语言排行榜:C、Java 和 Python 争夺第一
- linux的虚拟文件系统四(文件系统理论)
- java 计算包含中文字符串的真实长度
- 利用插槽solt实现蒙尘加载效果Vue
- 【缺陷管理】9:偶尔出现的缺陷如何处理?
- 短期学习就能月薪过万?IT培训套路揭秘,教育机构宣传是真是假
- jad文件的错误代码,分享