Created
February 11, 2020 01:14
-
-
Save yitonghe00/d7f97c78faf141a4744e1d3ba0dc3206 to your computer and use it in GitHub Desktop.
560. Subarray Sum Equals K (https://leetcode.com/problems/subarray-sum-equals-k/): Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Array + Brutal force solution | |
// Time: O(n ^ 2), 212ms | |
// Space: O(1), 40.6mb | |
class Solution { | |
public int subarraySum(int[] nums, int k) { | |
int ans = 0; | |
for(int i = 0; i < nums.length; i++) { | |
int sum = 0; | |
for(int j = 0; i + j < nums.length; j++) { | |
sum += nums[i + j]; | |
if(sum == k) ans++; | |
} | |
} | |
return ans; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Array + Hash table solution: store the <prefix sum, count> in a table; idea like 1 two sum | |
// Time: O(n), 11ms | |
// Space: O(n), 42.3mb | |
class Solution { | |
public int subarraySum(int[] nums, int k) { | |
int ans = 0; | |
// Init the <sum, count> table | |
Map<Integer, Integer> table = new HashMap<>(); | |
table.put(0, 1); | |
int sum = 0; | |
for(int i = 0; i < nums.length; i++) { | |
sum += nums[i]; | |
// Look up the table for prefix with a sum of sum - k: sum(i,j) = sum(0,j) - sum(0,i) | |
if(table.containsKey(sum - k)) ans += table.get(sum - k); | |
table.put(sum, table.getOrDefault(sum, 0) + 1); | |
} | |
return ans; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment