All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0501_0600.s0560_subarray_sum_equals_k.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0501_0600.s0560_subarray_sum_equals_k;

// #Medium #Top_100_Liked_Questions #Array #Hash_Table #Prefix_Sum #Data_Structure_II_Day_5_Array
// #Big_O_Time_O(n)_Space_O(n) #2022_08_03_Time_21_ms_(98.97%)_Space_46.8_MB_(88.27%)

import java.util.HashMap;
import java.util.Map;

/**
 * 560 - Subarray Sum Equals K\.
 *
 * Medium
 *
 * Given an array of integers `nums` and an integer `k`, return _the total number of continuous subarrays whose sum equals to `k`_.
 *
 * **Example 1:**
 *
 * **Input:** nums = [1,1,1], k = 2
 *
 * **Output:** 2 
 *
 * **Example 2:**
 *
 * **Input:** nums = [1,2,3], k = 3
 *
 * **Output:** 2 
 *
 * **Constraints:**
 *
 * *   1 <= nums.length <= 2 * 104
 * *   `-1000 <= nums[i] <= 1000`
 * *   -107 <= k <= 107
**/
public class Solution {
    public int subarraySum(int[] nums, int k) {
        int tempSum = 0;
        int ret = 0;
        Map sumCount = new HashMap<>();
        sumCount.put(0, 1);
        for (int i : nums) {
            tempSum += i;
            if (sumCount.containsKey(tempSum - k)) {
                ret += sumCount.get(tempSum - k);
            }
            if (sumCount.get(tempSum) != null) {
                sumCount.put(tempSum, sumCount.get(tempSum) + 1);
            } else {
                sumCount.put(tempSum, 1);
            }
        }
        return ret;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy