Subarray Sum Equals K LT560
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
- The length of the array is in range [1, 20,000].
- The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
Idea 1. Brute force: find the sum of each subarray represented by a pair of integer 0 <= i <= j < nums.length, increment the count once the sum is equal to k.
Time complexity: O(n2)
Space complexity: O(1)
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
for(int i = 0; i < nums.length; ++i) {
int sum = 0;
for(int j = i; j < nums.length; ++j) {
sum += nums[j];
if(sum == k) {
++count;
}
}
}
return count;
}
}
1.b using cumulative sum
Time complexity: O(n2)
Space complexity: O(n)
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
int sz = nums.length;
int[] cumuSum = new int[sz];
cumuSum[0] = nums[0];
for(int i = 1; i < sz; ++i) {
cumuSum[i] = cumuSum[i-1] + nums[i];
}
for(int i = 0; i < sz; ++i) {
if(cumuSum[i] == k) {
++count;
}
for(int j = i+1; j < sz; ++j) {
if(cumuSum[j] - cumuSum[i] == k) {
++count;
}
}
}
return count;
}
}
The little trick here: cumuSum[i] = sum(nums[0], ...nums[i-1]), the sum of elements for the subarray nums[i:j] = cumuSum[j+1] - cumuSum[i], otherwise need to deal with the case when subarray starts at 0 index.
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
int sz = nums.length;
int[] cumuSum = new int[sz+1];
for(int i = 1; i <= sz; ++i) {
cumuSum[i] = cumuSum[i-1] + nums[i-1];
}
for(int i = 0; i < sz; ++i) {
for(int j = i+1; j <= sz; ++j) {
if(cumuSum[j] - cumuSum[i] == k) {
++count;
}
}
}
return count;
}
}
Idea 2. Extending the cumulative sum idea listed on 1.b, the sum of elements between i and j is cumuSum[j] - cumuSum[i-1], if it is equal to k, then the subarray is found. We can make use of hashmap to store the pair of (sum, number of occurences of sum). Everytime the element is added to the cumulative sum, the number of times a subarray with sum k has occured is determined by the number of times sum - k has occured and then increment the count, in the meantime update the number of occurences of the cumulative sum.
Time complexity: O(n)
Space complexity: O(n)
Be careful, the cumulative sum start at 0, we need to check first and increment accordingly, as we don't have previous sum = 0
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
Map<Integer, Integer> sumCounts = new HashMap<>();
int sum = 0;
for(int num: nums) {
sum += num;
if(sum == k) {
++count;
}
count += sumCounts.getOrDefault(sum - k, 0);
sumCounts.put(sum, sumCounts.getOrDefault(sum, 0) + 1);
}
return count;
}
}
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
Map<Integer, Integer> sumCounts = new HashMap<>();
int sum = 0;
for(int num: nums) {
sum += num;
if(sum == k) {
++count;
}
count += sumCounts.getOrDefault(sum - k, 0);
sumCounts.put(sum, sumCounts.getOrDefault(sum, 0) + 1);
}
return count;
}
}
little trick like 1.b, add 0 to the hashmap, save the check on line 10 above, code is slightly more concise.
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
Map<Integer, Integer> sumCounts = new HashMap<>();
sumCounts.put(0, 1);
int sum = 0;
for(int num: nums) {
sum += num;
count += sumCounts.getOrDefault(sum - k, 0);
sumCounts.put(sum, sumCounts.getOrDefault(sum, 0) + 1);
}
return count;
}
}
Subarray Sum Equals K LT560的更多相关文章
- Subarray Sum & Maximum Size Subarray Sum Equals K
Subarray Sum Given an integer array, find a subarray where the sum of numbers is zero. Your code sho ...
- Subarray Sum & Maximum Size Subarray Sum Equals K && Subarray Sum Equals K
Subarray Sum Given an integer array, find a subarray where the sum of numbers is zero. Your code sho ...
- [LeetCode] 325. Maximum Size Subarray Sum Equals k 和等于k的最长子数组
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...
- leetcode 560. Subarray Sum Equals K 、523. Continuous Subarray Sum、 325.Maximum Size Subarray Sum Equals k(lintcode 911)
整体上3个题都是求subarray,都是同一个思想,通过累加,然后判断和目标k值之间的关系,然后查看之前子数组的累加和. map的存储:560题是存储的当前的累加和与个数 561题是存储的当前累加和的 ...
- [LeetCode] Subarray Sum Equals K 子数组和为K
Given an array of integers and an integer k, you need to find the total number of continuous subarra ...
- [leetcode]560. Subarray Sum Equals K 和为K的子数组
Given an array of integers and an integer k, you need to find the total number of continuous subarra ...
- [LeetCode] 560. Subarray Sum Equals K 子数组和为K
Given an array of integers and an integer k, you need to find the total number of continuous subarra ...
- [LeetCode] Maximum Size Subarray Sum Equals k 最大子数组之和为k
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...
- LeetCode 560. Subarray Sum Equals K (子数组之和等于K)
Given an array of integers and an integer k, you need to find the total number of continuous subarra ...
随机推荐
- Mybatis返回List<Map<K,V>>
最终映射的字段名 会被作为 hashMap 的 key , <!-- TODO 测试返回 HashMap--> <resultMap id="testResultMap&q ...
- 在centos xmanager工具环境下启动 xwindow
# 安装epel源 [root@linuxidc ~]# yum install -y epel-release # 安装lightdm和Xfce 1.安装 lightdm sudo yum inst ...
- DRDS 概述
DRDS 概述 更新时间:2017-08-04 13:53:50 分布式关系型数据库服务(Distributed Relational Database Service , 简称 DRDS ) ...
- 安装 pygame,找不到Python version 2.7
今天在安装pygame时出错,提示“Python version 2.7 required, which was not found in the registry”,经过网上查找资料后发现只需要新建 ...
- ucore-lab1-练习3report
练习3.分析bootload进入保护模式的过程 0. BIOS通过读取硬盘主引导扇区到内存,并跳转到对应内存中的位置,也就是从’%cs=0 $pc=0x7c00‘进入并执行bootloader,boo ...
- Hudson 打包部署到Was上特别慢
一.找问题点 1.打包很快,到部署很慢 2.部署到其他was一样很慢 二.解决 经过寻找,网上找出以下一段话: 问题出在web.xml,web.xml中的版本信息不对,要根据你的servlet版本和运 ...
- 静态方法调用内部类时候的new 问题
package tool; /** * 静态方法调用内部类时候的new 问题 */ public class aa { // 静态方法 // 静态方法new 有问题 public static voi ...
- TOJ1302: 简单计算器 && TOJ 4873: 表达式求值&&TOJ3231: 表达式求值
这些都是应用Python的eval函数的一些题目! TOJ1302传送门:http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=show ...
- cisco 割接脚本中ssh的key生成问题
昨晚割接某企业4506更换4507过程中,运维工程师问crypto key generate rsa这个步骤是不是要单独出来进行刷配置,其实不需要的单独出来的crypto key generate r ...
- Ionic3错误: StaticInjectorError[HttpModule]: NullInjectorError: No provider for HttpModule!
先在app.module.ts中导入HttpModule,才能在构造函数中注入Http. Ionic自动构建项目时,并没有导入HttpModule. 解决方案:打开app.module.ts,加入导入 ...