Subarray Sum Equals K

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2

Note:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

题目理解:

给定一个字符串,问有多少个连续子串的和等于k

解题思路:

使用一个字典,key是子数组nums(0 ~ i)的和,value是这个和出现的次数,因为数组中的数可能有负数,因此可能nums(0 ~ m)和nums(0 ~ n)的和是相等的,遍历这个数组,在看到nums[i + 1]的时候,nums[i+1] - k出现的次数,就是nums(x ~ i+1)和为k的次数

代码如下:

class Solution {
    public int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> left = new HashMap<Integer, Integer>();
        left.put(0, 1);
        int sum = 0, res = 0;
        for(int num : nums) {
        	sum += num;
        	int key = sum - k;
        	if(left.containsKey(key))
        		res += left.get(key);
        	left.put(sum, left.getOrDefault(sum, 0) + 1);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37889928/article/details/82831818