Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

209. Minimum Size Subarray Sum #73

Open
tech-cow opened this issue Jan 14, 2020 · 0 comments
Open

209. Minimum Size Subarray Sum #73

tech-cow opened this issue Jan 14, 2020 · 0 comments

Comments

@tech-cow
Copy link
Owner

209. Minimum Size Subarray Sum

公瑾回来刷题咯

image

"""
[start] 12:34

Problem Solving Thought Process:

1. Brute Force
Using 2 for loops to find out 2 element that sums up to the target
Constantly update the minimum length in a globalMin

globalMin = infi
for i -> n
    for j -> n
        cur_sum += nums[j]
        if cur_sum > target:
            globalMin = min(globalMin, cur_sum)
            break
return globalMin

Time: O(N^2)
Space: O(1)


2. Two Pointer 
We can potentially only iterate "j" from beginning to end once by moving "i" along the way

Time: O(N)
Space: O(1)
"""

#[Coding Start] 12:39
#[Coding Finish] 12:43
#[Eyeballing code] 12:43 - 12:46
# Bug
"""
globalMin = float('inf')
curSum = 0
j = 0

for i in range(len(nums)):
    while j < len(nums) and curSum < target:
        curSum += nums[j]
        j += 1

    if curSum >= target:
        globalMin = min(globalMin, j - i)

    curSum -= nums[i]

return globalMin   ->  bug1. 如果没有找到合适的结果,应该返回0而不是初始值的infinite

fail testcases:

3
[1,1]
"""
        
class Solution(object):
    def minSubArrayLen(self, target, nums):      
        globalMin = float('inf')
        curSum = 0
        j = 0
        
        for i in range(len(nums)):
            while j < len(nums) and curSum < target:
                curSum += nums[j]
                j += 1
            
            if curSum >= target:
                globalMin = min(globalMin, j - i)
            
            curSum -= nums[i]
        
        return globalMin if globalMin != float('inf') else 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant