Subarray Sum Equals K

  • 0

    Click here to see the full article post

  • 0

    The codes in the last approach:

    if (map.containsKey(sum))
    map.put(sum, map.get(sum) + 1);
    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

    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

    @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);
        return count;

  • 0

    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.