和爲k的連續子數組的個數 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.spa

Example 1:get

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

Note:io

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

解決:class

①  累加數組。遍歷

class Solution {//280ms
    public int subarraySum(int[] nums, int k) {
        int res = 0;
        for (int i = 1;i < nums.length;i ++){
            nums[i] += nums[i - 1];
        }
        for (int i = 0;i < nums.length;i ++){
            if (nums[i] == k) res ++;
            for (int j = i - 1;j >= 0;j --){
                if (nums[i] - nums[j] == k) res ++;
            }
        }
        return res;
    }
}map

② 用一個哈希表來創建連續子數組之和跟其出現次數之間的映射,初始化要加入{0,1}這對映射,這是爲啥呢,由於咱們的解題思路是遍歷數組中的數字,用sum來記錄到當前位置的累加和,咱們創建哈希表的目的是爲了讓咱們能夠快速的查找sum-k是否存在,便是否有連續子數組的和爲sum-k,若是存在的話,那麼和爲k的子數組必定也存在,這樣當sum恰好爲k的時候,那麼數組從起始到當前位置的這段子數組的和就是k,知足題意,若是哈希表中實現沒有m[0]項的話,這個符合題意的結果就沒法累加到結果res中,這就是初始化的用途。哈希表

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

③ 整合上面兩種解法:數字

class Solution { //42ms     public int subarraySum(int[] nums, int k) {         if(nums == null || nums.length == 0) return 0;         int len = nums.length;         for(int i = 1; i < len; i ++){             nums[i] += nums[i - 1];         }         Map<Integer, Integer> map = new HashMap<>();         map.put(0, 1);         int res = 0;         for(int i = 0; i < len; i++){             if(map.containsKey(nums[i] - k)){                 res += map.get(nums[i] - k);             }             map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);         }         return res;     } }

相關文章
相關標籤/搜索