Skip to content

560. Subarray Sum Equals K #95

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
tech-cow opened this issue Feb 24, 2020 · 1 comment
Open

560. Subarray Sum Equals K #95

tech-cow opened this issue Feb 24, 2020 · 1 comment

Comments

@tech-cow
Copy link
Owner

560. Subarray Sum Equals K

'''
不懂的可以参考: https://leetcode-cn.com/problems/subarray-sum-equals-k/solution/hot-100-he-wei-kde-zi-shu-zu-python3-cong-bao-li-j/
[1:29] Start

Thought Process
1. [Brute Force]

for i -> n
    for j -> (i, n)
        find sum of nums[i:j + 1] == target

Time: O(N^3)


2. PreSum

for i -> n
    preSum = [0] * len(arr)
    for j -> (i, n):
        if preSum[j] - preSum[i] == k
            add to res

Time: O(N^2)


3. preSum

because: preSum[j] - preSum[i] == k

so: preSum[i] == preSum[j] - k

because we always iterate i before j
we store preSum[i] in hash
and while we iterate J, we do preSum[j] - k, and see if it's in hash.

Time: O(N)

'''
# preSum + O(N^2)
class Solution(object):
    def subarraySum(self, nums, target):
        if not nums: return 0
        n = len(nums)
        res = 0
        for i in range(n):
            preSum = 0
            for j in range(i, n):
                preSum += nums[j]
                if preSum == target:
                    res += 1
        return res
# preSum + hash O(N)
class Solution(object):
    def subarraySum(self, nums, target):
        if not nums: return 0
        dic = {0 : 1}
        preSum = 0
        res = 0
        for i in range(len(nums)):
            preSum += nums[i]
            if preSum - target in dic:
               res += dic[preSum - target]
            dic[preSum] = dic.get(preSum, 0) + 1   
        return res
@tech-cow tech-cow changed the title 560 560. Subarray Sum Equals K Feb 24, 2020
@tech-cow
Copy link
Owner Author

class Solution(object):
    def subarraySum(self, nums, k):
        res = 0
        n = len(nums)
        for i in range(n):
            preSum = 0
            for j in range(i, n):
                preSum += nums[j]
                if preSum == k:
                    res += 1
        return res
class Solution(object):
    def subarraySum(self, nums, k):
        dic = {0 : 1}
        n = len(nums)
        preSum = 0
        res = 0
        for i in range(n):
            preSum += nums[i]
            if preSum - k in dic:
                res += dic[preSum - k]        
            dic[preSum] = dic.get(preSum, 0) + 1
                
        return res

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant