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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值