Skip to content

Commit

Permalink
update 560 java
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Dec 21, 2024
1 parent 318bc02 commit 9667385
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,46 @@ public int subarraySum_0_1(int[] nums, int k) {
return cnt;
}

// V0-2
// IDEA : presum + hashmap
public int subarraySum_0_2(int[] nums, int k) {

if (nums.length == 1){
if (nums[0] == k){
return 1;
}
return 0;
}

int presum = 0;
int cnt = 0;
/**
* map{ presum : cnt}
*/
Map<Integer, Integer> map = new HashMap<>();
// init map as below
map.put(0,1);

for (int i = 0; i < nums.length; i++){
int cur = nums[i];
presum += cur;
/**
* sum(i,j) = presum(j+1) - presum(i)
*
* -> presum(j+1) - presum(i) = k
* -> presum(i) = presum(j+1) - k
*/
if (map.containsKey(presum - k)){
cnt += map.get(presum - k);
}

map.put(presum, map.getOrDefault(presum, 0)+1);
}

return cnt;
}


// V1
// IDEA : HASH MAP
// https://leetcode.com/problems/subarray-sum-equals-k/solutions/6143642/java-beats-9983-by-mohamedhazem3-9yj6/
Expand Down
50 changes: 50 additions & 0 deletions leetcode_java/src/main/java/dev/workspace6.java
Original file line number Diff line number Diff line change
Expand Up @@ -360,4 +360,54 @@ public boolean checkSubarraySum(int[] nums, int k) {
return false;
}

// LC 560
// https://leetcode.com/problems/subarray-sum-equals-k/description/
// 3.37 - 3.47 pm
/**
* Given an array of integers nums and an integer k,
* return the total number of subarrays whose sum equals to k.
*
* A subarray is a contiguous non-empty
* sequence of elements within an array.
*
* IDEA : presum + hashmap
*/
public int subarraySum(int[] nums, int k) {

if (nums.length == 1){
if (nums[0] == k){
return 1;
}
return 0;
}

int presum = 0;
int cnt = 0;
/**
* map{ presum : cnt}
*/
Map<Integer, Integer> map = new HashMap<>();
// init map as below
map.put(0,1);

for (int i = 0; i < nums.length; i++){
int cur = nums[i];
presum += cur;
/**
* sum(i,j) = presum(j+1) - presum(i)
*
* -> presum(j+1) - presum(i) = k
* -> presum(i) = presum(j+1) - k
*/
if (map.containsKey(presum - k)){
cnt += map.get(presum - k);
}

map.put(presum, map.getOrDefault(presum, 0)+1);
}

return cnt;
}


}

0 comments on commit 9667385

Please sign in to comment.