preSum + HashMap Java


  • 0
    V
    public class Solution {
        public int subarraySum(int[] nums, int k) {
            if (nums.length == 0) return 0;
            int count = 0, preSum = 0;
            Map<Integer, Integer> sumToCountMap = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                preSum += nums[i];
                if (preSum == k) count++;
                
                if (sumToCountMap.containsKey(preSum - k)) count += sumToCountMap.get(preSum - k);
                if (!sumToCountMap.containsKey(preSum)) sumToCountMap.put(preSum, 1);
                else sumToCountMap.put(preSum, sumToCountMap.get(preSum) + 1);
            }
            
            return count;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.