Subarray Sum Equals K


  • 0

    Click here to see the full article post


  • 0
    A

    The codes in the last approach:

    if (map.containsKey(sum))
    map.put(sum, map.get(sum) + 1);
    else
    map.put(sum, 1);

    may be better like this:

    map.put(sum, map.getOrDefault(sum, 0) + 1);


  • 0

    @amoker I have updated the code. Thanks.


  • 0
    F

    Hi, in the last method, why I change the order of if and put, I will get an error? Since the case of k = 0?


  • 0

    @FF_TI Yes only for k=0, it will give false result.


  • 0
    A

    @FF_TI No need of put(0,1):

    public int subarraySum(int[] nums, int k) {
        int count=0,sum=0;
        Map<Integer,Integer> hm = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            hm.put(sum, hm.getOrDefault(sum,0)+1);
            sum+=nums[i];
            count+=hm.getOrDefault((sum-k),0);
        }
        return count;
    }

  • 0
    D

    Why is this tagged "Map"? What's the difference between that and the tag "Hash table"?


Log in to reply
 

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