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. dns隧道 dns2tcpd

    有些网络的防火墙设置只允许端口53的UDP流量,就不能通过tcp搭建隧道,这种情况下我们可以通过UDP搭建DNS隧道,通过搭建一个DNS服务器委派的子域,这个子域因为使我们自己搭建的主机,这时候就可以 ...

  2. jvisual修改内存大小

    jvisual(Java VisualVM)导入dump文件内存不足解决办法: 当通过jvusual调整-Xmx参数: c:/program files/java/jdk1.6/lib/visualv ...

  3. JMeter学习(三十一)non-gui模式运行(转载)

    转载自 http://www.cnblogs.com/yangxia-test 必须要了解的一些信息 既然是要通过non-gui模式运行,那么我们就不得不去了解下在non-gui模式下jmeter命令 ...

  4. 第三章 列表(a)接口与实现

  5. 【转】 mysql 数据优化

    数据库优化离不开索引,如何理解索引? ---------------------------------------------------------------------------- 可以参考 ...

  6. POJ-3279.Fliptile(二进制状态压缩 + dfs) 子集生成

    昨天晚上12点刷到的这个题,一开始一位是BFS,但是一直没有思路.后来推了一下发现只需要依次枚举第一行的所有翻转状态然后再对每个情况的其它田地翻转进行暴力dfs就可以,但是由于二进制压缩学的不是很透, ...

  7. c#: List.Sort()实现稳固排序(stable sort)

    1. 源起: KV 7.0加入列表管理功能,处理排序问题时,对空列表执行按大小.日期.长度排序发现,其中次序会发生改变,令人纳闷. 没天理呀,不应该啊!List.Sort()方法,它为什么? 对此问题 ...

  8. PLSQL连接Oracle数据库问题及详解

    一.Oracle数据库安装步骤参考:https://jingyan.baidu.com/article/363872eccfb9266e4aa16f5d.html 二.Oracle客户端安装:http ...

  9. Practice 10

    通过关键字extends来创建一个类的子类.一个类通过关键字implements声明自己使用一个或者多个接口. settext是根据数组新建的pets[1]object来的,对其调用抽象方法talk, ...

  10. 数据库中where与having区别

    having 和where 都是用来筛选用的 having 是筛选组 而where是筛选记录 他们有各自的区别 1>当分组筛选的时候 用having 2>其它情况用where------- ...