930. Binary Subarrays With Sum

양성준·2025년 5월 5일

코딩테스트

목록 보기
40/102

문제

https://leetcode.com/problems/binary-subarrays-with-sum/description/

풀이

class Solution {
    public int numSubarraysWithSum(int[] nums, int goal) {
        Map<Integer, Integer> map = new HashMap<>();
        int sum = 0;
        int answer = 0;
        map.put(0, 1);

        for(int n : nums) {
            sum += n;
            answer += map.getOrDefault(sum - goal, 0);
            map.put(sum, map.getOrDefault(sum, 0) + 1);
        }

        return answer;
    }
}
profile
백엔드 개발자

0개의 댓글