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. ./configure: error: the HTTP rewrite module requires the PCRE library解决

    ./configure: error: the HTTP rewrite module requires the PCRE library解决   有时候,我们需要单独安装nginx,来处理大量的下载 ...

  2. pta6-17(另类堆栈)

    题目链接:https://pintia.cn/problem-sets/1101307589335527424/problems/1101313244872126464 题意:一种新的堆栈,用Top表 ...

  3. TZOJ 3659 神奇的探险之旅(有向无环每个点只能经过一次最长路dij)

    描述 我们正在设计这样的一款儿童探险游戏:游戏由很多故事场景组成,每个场景中都有一个问题,游戏根据玩家的回答将进入下一场景,经过巧妙的设计,我们保证在一次“探险旅行”中,不会重复的进入任何相同的场景, ...

  4. 【剑指offer】题目二

    //实现一个函数:把字符串中的每个空格替换成"%20".例如输入"We are happy."则输出"We%20are%20happy." ...

  5. server2003远程桌面设置一个用户

    开始--程序--管理工具--终端服务配置--限制每个用户使用一个会话

  6. swift 4.2 - 根据字符串 push指定控制器

    俩个方法 1. 创建类写成 类方法 import UIKit /* * 注释:获得VC * 1.字符串 和使用的控制器,直接跳转 * 2.用过字符串获得对应VC */ class JYGetPushV ...

  7. java 线程Thread 技术--线程方法详解

    Thread 类常用的方法与Object类提供的线程操作方法:(一个对象只有一把锁

  8. ios 获取当前时间

    1.第一种返回的时间是一个整个的字符串. NSDate *timeDate = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateForm ...

  9. .net项目错误:找不到方法:“System.Net.Http.HttpClient stellar_dotnet_sdk.Server.get_HttpClient()

    1.由于在项目里面引用了一个 新的项目stellar_dotnet_sdk,在  return new StellarWallet(ConvertToWalletSetting(coin));   的 ...

  10. .NET垃圾回收机制

    在.net 编程环境中,系统的资源分为托管资源和非托管资源.  对于托管的资源的回收工作,是不需要人工干预回收的,而且你也无法干预他们的回收,所能够做的只是了解.net CLR如何做这些操作.也就是说 ...