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:

  1. The length of the array is in range [1, 20,000].
  2. 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的更多相关文章

  1. 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 ...

  2. 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 ...

  3. [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 ...

  4. 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题是存储的当前累加和的 ...

  5. [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 ...

  6. [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 ...

  7. [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 ...

  8. [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 ...

  9. 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 ...

随机推荐

  1. Java的map键值对的用法,map的遍历,Entry对象的使用

    思路: 1.定义集合 2.存储数据 3.添加元素 4.遍历 4.1将需要遍历的集合的键封装到set集合中(这用到了entrySet方法,和Entry对象) 4.2声明迭代器或者用for增强循环 4.3 ...

  2. versionCode & versionName

    [versionCode & versionName] Android的版本可以在androidmainfest.xml中定义,主要有android:versionCode和android:v ...

  3. TP3.23 与Laypage 结合进行分页

    demo地址:http://tp.ytlwin.top 控制器 <?php namespace Home\Controller; use Think\Controller; class Inde ...

  4. WINDOWS防火墙开启后Ping不通

    WINDOWS系统由于安全考虑,当开启防火墙时,默认不允许外主机对其进行ping功能,即别的电脑ping不通本机.别的主机ping不通本机是因为本机的防火墙关闭了ICMP回显功能,只要把这回显功能打开 ...

  5. 设置input标签的placeholder的样式

    设置input样式代码: input::-webkit-input-placeholder{ /*WebKit browsers*/ color: red; } input::-moz-input-p ...

  6. ceph luminous 新功能之内置dashboard 之 mgr功能模块配置

    前言 ceph luminous版本新增加了很多有意思的功能,这个也是一个长期支持版本,所以这些新功能的特性还是很值得期待的,从底层的存储改造,消息方式的改变,以及一些之前未实现的功能的完成,都让ce ...

  7. unity农场模拟经营游戏源码

    下载地址: https://item.taobao.com/item.htm?spm=a1z10.5-c-s.w4002-12305352547.10.25ca3c4eWAibvf&id=56 ...

  8. Node使用 Express框架,实现文件上传

    一 安装依赖包 npm install multer --save 二 客户端上传文件 <!DOCTYPE html> <html> <head> <meta ...

  9. redis其他相关知识

    Redis的安全性 因为redis速度很快,所以在一台比较好的服务器下,一个外部用户在一秒内可以进行15W次的密码尝试,这意味着你需要设定非常强大的密码来防止暴力破解. vim编辑redis.conf ...

  10. MVC学习(四)几种分页的实现(1)

     这里,我使用的是Code-First,MVC3. 我们在数据库里建一个表MyTestPages,只有一个整型字段Id. 在写一个Model类MyTestPages,代码如下 public class ...