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 ...
随机推荐
- U3D框架—单例框架
写程序应遵循的原则:高内聚(内容的聚合),低耦合(功能与功能之间的联系) 代码里尽量不要有冗余:既重复,没有用的代码 using System.Collections; using System.Co ...
- U3D组件------CharacterController(角色控制器)
角色控制器中有碰撞体和刚体的属性 Slope Limit:角色能爬的斜坡的坡度限制 Step Offset:角色走台阶的高度 Skin Width:当场景里面出现多个角色控制器的时候,两个对象在接触的 ...
- day21 xml模块 ATM+购物车
1. xml模块 <father name="jack"> # 属性的值必须加双引号 <son> 标签的关闭顺序,与开启顺序相反, 最先开启的最后关闭,最后 ...
- Java 读写Properties配置文件(转)
转自:http://www.cnblogs.com/xudong-bupt/p/3758136.html
- PHP 获取 IE浏览器版本号
function getIEBrowserVersion(){ $agent = strtolower($_SERVER['HTTP_USER_AGENT']); if(strpos($agent, ...
- Python_变量命名
Python的变量命名 变量的命名的原则一直都是我这种小白的头疼事,好几条,根本记不住...... 为了解决大家的头疼问题,今天想出来一个好办法,那就是:身边常备头疼片.......(哈哈哈,开玩笑的 ...
- 17. Letter Combinations of a Phone Number (backtracking)
Given a digit string, return all possible letter combinations that the number could represent. A map ...
- 137. Single Number II (Bit)
Given an array of integers, every element appears three times except for one. Find that single one. ...
- c#的Boolean.Parse用法
bool val; string input; input = bool.TrueString; val = bool.Parse(input); Console.WriteLine("'{ ...
- RxJS之过滤操作符 ( Angular环境 )
一 take操作符 只发出源 Observable 最初发出的的N个值 (N = count). 如果源发出值的数量小于 count 的话,那么它的所有值都将发出.然后它便完成,无论源 Observa ...