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. Spring Boot application.yml bootstrap.yml

    yml与properties 其实yml和properties文件是一样的原理,且一个项目上要么yml或者properties,二选一的存在. 推荐使用yml,更简洁. bootstrap与appli ...

  2. html中表单的应用

    2.表单 ***** 表单作用: 用于显示.收集信息,并将信息提交到服务器 表单两大部分: 1.实现数据交互的可见界面元素,即表单控件 2.提交表单后的处理操作 1.如何实现表单 语法:<for ...

  3. 《java与模式》阅读笔记01

    这次我读了前两章的内容,就如书名所言,这本书主要将的就是java中的模式,在书中的序言就把所有的模式都介绍了一下,主要有, 1.创建模式:简单工厂模式,工厂方法模式,抽象工厂模式,建造模式 2.行为模 ...

  4. 【OpenGL】glsl、glew、glfw

    glsl: OpenGL着色语言(OpenGL Shading Language)是用来在OpenGL中着色编程的语言,也即开发人员写的短小的自定义程序,他们是在图形卡的GPU (Graphic Pr ...

  5. Mysql 5.7 弱密码限制,及创建用户无密码用户

    一.介绍 1.haproxy Mysql 需要一个无密码登录的mysql用户. 2.Mysql 5.7 版本默认安装了 validate_password 插件,作用:要求密码的复杂度. 3.创建用户 ...

  6. Codeforces Beta Round #76 (Div. 2 Only)

    Codeforces Beta Round #76 (Div. 2 Only) http://codeforces.com/contest/94 A #include<bits/stdc++.h ...

  7. leetcode 443. String Compression

    下面反向遍历,还是正向好. void left(vector<char>& v, bool p(int)) { ; ; ; while (del < max_index) { ...

  8. [leetcode]692. Top K Frequent Words K个最常见单词

    Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted b ...

  9. c++ 中map 的find 函数用法

    Map中,find函数用来定位数据出现位置,当含有该数据,即查找成功时,返回数据所在未知的迭代器, 如果查找失败,则返回end()函数所在的迭代器,因此用是否等于end来判断是否查找成功. 程序示例: ...

  10. 42-字符串到json 的错误 com.alibaba.fastjson.JSONObject cannot be cast to java.lang.String

    json: {"updated_at":1551780617,"attr":{"uptime_h":3,"uptime_m&quo ...