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,2,3}, k = 3
Output: 2
Approach
Java
import java.util.HashMap;public class SubarraySumEqualsK {public static void main(String[] args) {int[] nums = { 1, 2, 3 };int k = 3;System.out.println(subarraySum(nums, k));}// find the number of subarray whose// sum is equal to kstatic int subarraySum(int[] nums, int k) {HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();int sum = 0, res = 0;for (int i = 0; i < nums.length; i++) {sum += nums[i];if (sum == k)res++;if (map.containsKey(sum - k))res += map.get(sum - k);map.put(sum, map.getOrDefault(sum, 0) + 1);}return res;}}
C++
#include <bits/stdc++.h>using namespace std;//find the number of subarray whose//sum is equal to kint subarraySum(vector<int> &nums, int k){unordered_map<int, int> ump;int sum = 0, res = 0;for (int i = 0; i < nums.size(); i++){sum += nums[i];if (sum == k)res++;if (ump.find(sum - k) != ump.end())res += ump[sum - k];ump[sum]++;}return res;}int main(){vector<int> nums = {1, 2, 3};int k = 3;cout << subarraySum(nums, k);return 0;}
No comments:
Post a Comment