g0501_0600.s0560_subarray_sum_equals_k.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
The newest version!
package g0501_0600.s0560_subarray_sum_equals_k;
// #Medium #Top_100_Liked_Questions #Array #Hash_Table #Prefix_Sum #Data_Structure_II_Day_5_Array
// #Big_O_Time_O(n)_Space_O(n) #2024_11_17_Time_22_ms_(95.17%)_Space_47.2_MB_(6.13%)
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int subarraySum(int[] nums, int k) {
int tempSum = 0;
int ret = 0;
Map sumCount = new HashMap<>();
sumCount.put(0, 1);
for (int i : nums) {
tempSum += i;
if (sumCount.containsKey(tempSum - k)) {
ret += sumCount.get(tempSum - k);
}
if (sumCount.get(tempSum) != null) {
sumCount.put(tempSum, sumCount.get(tempSum) + 1);
} else {
sumCount.put(tempSum, 1);
}
}
return ret;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy