Skip to content

Latest commit

 

History

History
20 lines (18 loc) · 527 Bytes

930.md

File metadata and controls

20 lines (18 loc) · 527 Bytes

930. Binary Subarrays With Sum

Solution 1 (time O(n), space O(n))

class Solution {
    public int numSubarraysWithSum(int[] nums, int goal) {
        Map<Integer, Integer> d = new HashMap<Integer, Integer>();
        d.put(0, 1);
        int ans = 0;
        int cur_sum = 0;
        for (int i = 0; i < nums.length; i++) {
            cur_sum += nums[i];
            ans += d.getOrDefault(cur_sum - goal, 0);
            d.put(cur_sum, d.getOrDefault(cur_sum, 0) + 1);
        }
        return ans;
    }
}