leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

Sliding Windows

Open tech-cow opened this issue 5 years ago • 2 comments

tech-cow avatar Feb 24 '20 15:02 tech-cow

209. Minimum Size Subarray Sum

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
        

tech-cow avatar Feb 24 '20 15:02 tech-cow

3. Longest Substring Without Repeating Characters

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        globalMax = -float('inf')
        globalSet = set()
        j = 0
        
        for i in range(len(s)):
            while j < len(s) and s[j] not in globalSet:
                globalSet.add(s[j])
                globalMax = max(globalMax, len(globalSet))
                j += 1
            globalSet.remove(s[i])
        
        return globalMax if globalMax != -float('inf') else 0

tech-cow avatar Feb 24 '20 15:02 tech-cow