1. 程式人生 > >Leetcode: Subarray Sum Equals K\\\Binary Subarrays With Sum

Leetcode: Subarray Sum Equals K\\\Binary Subarrays With Sum

Problem

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

Solution

我們用一個HashMap<preSum,count>來儲存:和為preSum的subarray的數量。 通過遍歷整個輸入的nums陣列,不斷更新HashMap。 在遍歷到時間t時,nums[0]+nums[1]+...+nums[t1]=preSumnums[0]+nums[1]+...+nums[t-1] = preSum,在這個時刻之前共有HashMap[V]HashMap[V]個indices jj 使得nums[0]+nums[1]+...+nums[j]=Vnums[0]+nums[1]+...+nums[j] = V

,且nums[j]+...+nums[t1]=preSumVnums[j]+...+nums[t-1] =preSum- V。 所以在每個時刻我們都將HashMap[preSumk]HashMap[preSum-k]累加到我們的結果中。

class Solution:
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        count = collections.Counter()
        count[0] = 1
        preSum = 0
        ans = 0
        for x in nums:
            preSum += x
            ans += count[preSum-k]
            count[preSum] += 1
        return ans

另一道題解法和本題相同:

Problem

In an array A of 0s and 1s, how many non-empty subarrays have sum S?

Example 1:

Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]

Note:

A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.