【leetcode】560. Subarray Sum Equals K

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/86645296

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

解题思路:利用HashMap

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

tips:map的key存储子序列的和,当出现关键字已经存在的子序列时,需要获得该关键字的值再加一的原因是:此时的子序列可以选择与之前出现的子序列和为k的子序列组合,也可以不组合。,

猜你喜欢

转载自blog.csdn.net/ghscarecrow/article/details/86645296
今日推荐