share my java solution! using hashmap


  • 0
    C
    
    public class Solution {
        public int subarraySum(int[] nums, int k) {
              HashMap<Integer,Integer> map=new HashMap<>();
              int sum=0;
              map.put(0,1);
              
              int count=0;
              for(int i=0;i<nums.length;i++){
                  sum+=nums[i];
                  if(map.containsKey(sum-k)){
                      count+=map.get(sum-k);
                  }
                  map.put(sum,map.getOrDefault(sum,0)+1);
              }
              
              return count;
        }
    }
    
    

Log in to reply
 

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