LeetCode 560. Subarray Sum Equals K

[Med] LeetCode 560. Subarray Sum Equals K

链接: https://leetcode.com/problems/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.

给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

Note:

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

Tag: Pre-Sum, HashMap
解题思路
这道题目是一个非常经典的pre-sum的做法。我们构建一个hashmap, 里面储存的是在遍历到i位之前的所有从0开始的subarray的和。比如说当i为3时,Map当中会储存[array[0]], [array[0]+array[1]], [array[0]+array[1]+array[2]]的三个subarray的和。我们在遍历数组的时候同时要累加当前遍历到的元素。total+=array[i]。然后此时我们只需要判断map当中是否出现过total-k就知道在这之前是否有subarray可以和当前total相减取得K这个值了。同时我们也可以知道在这之前有多少个subarray。

解法一:

class Solution {
    public int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> presum = new HashMap<>();
        //要添加0的原因是空的subarray总和就是0
        presum.put(0, 1);
        int total = 0, res = 0;
        
        for(int num : nums){
            total+=num;
            if(presum.containsKey(total-k)){
                res+=presum.get(total-k);
            }
            presum.put(total, presum.getOrDefault(total, 0)+1);
            
        }
        
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值