欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 560 Subarray Sum Equals K (hash)

程序员文章站 2022-07-15 14:15:35
...

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].

题目链接:https://leetcode.com/problems/subarray-sum-equals-k/

题目分析:前缀和,hashmap,没了

12ms,时间击败99.86%

class Solution {
    
    public int subarraySum(int[] nums, int k) {
        HashMap<Integer, Integer> mp = new HashMap<>();
        int[] sum = new int[nums.length + 1];
        for (int i = 1; i <= nums.length; i++) {
            sum[i] = sum[i - 1] + nums[i - 1];
        }
        int ans = 0;
        for (int i = 0; i < sum.length; i++) {
            if (mp.containsKey(sum[i] - k)) {
                ans += mp.get(sum[i] - k);
            }
            mp.put(sum[i], mp.getOrDefault(sum[i], 0) + 1);
        }
        return ans;
    }
}

 

相关标签: hash