Subarray Sum Equals 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.數組

Example 1:spa

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

Note:code

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

分析

這道題開始並不容易想,由於不是典型的那種能夠用DP解決的子數組類型的題。因爲求的是子subarray和爲K的總個數,只能想辦法找出全部和爲K的子數組,而後返回個數就能夠。get

那麼關鍵點就是怎麼找出全部和爲K的子數組,bruce force的方法顯然不可行。突破點就是咱們能夠把任意子數組的裏面全部元素的和轉化爲兩個子數組累計元素和之差,固然這個兩個子數組指的是頭元素是大數組第一個元素的連續子數組。這樣一來,咱們用一個HashMap來記錄每一個子數組元素和對應的次數就能夠了。io

咱們從頭開始讀數組,記錄下累計元素之和,把每次的和存在HashMap中,經過HashMap在每次讀的過程當中咱們能夠找出是否前面存在一個數組與當前數組之差等於K,這樣咱們就能夠找出因此子數組之和爲K的狀況。因爲存在前面子數組和相同的狀況,咱們用HashMap記錄每一個和對應的次數就能夠了。class

複雜度

time: O(n), space: O(n)map

代碼

class Solution {
    public int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        int sum = 0;
        int count = 0;
        for (int num : nums) {
            sum += num;
            if (map.containsKey(sum - k)) {
                count += map.get(sum - k);
            }
            map.put(sum, map.getOrDefault(sum, 0) + 1);
        }
        return count;
    }
}
相關文章
相關標籤/搜索