leetcode刷题笔记-two pointer

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sengo_GWU/article/details/86328264

713. Subarray Product Less Than K

Time is O(N) and space is O(1)

class Solution(object):
    def numSubarrayProductLessThanK(self, nums, k):
        i = re = product = 0
        for j, v in enumerate(nums):
            product *= v
            while i <= j and product >= k:
                product /= nums[i]
                i += 1
            if product < k:
                re += j - i + 1
        return re
        

1004. Max Consecutive Ones III

这题很简单,一遍过,但是是看了标签才知道是two pointer的解法。要重新整理一遍two pointer的题目做到一看就知道是这种题型的。 

class Solution(object):
    def longestOnes(self, A, K):
        left = 0
        count = 0
        re = 0
        for i, v in enumerate(A):
            if v == 0:
                count += 1
            
            while count > K:
                if A[left] == 0:
                    count -= 1
                left += 1
            re = max(re, i-left+1)
        return re

567. Permutation in String

class Solution(object):
    def checkInclusion(self, s1, s2):
        count = collections.Counter(s1)
        n = len(s1)
        for i in xrange(len(s2)-n+1):
            if collections.Counter(s2[i: i+n]) == count:
                return True
        return False

904. Fruit Into Baskets

class Solution(object):
    def totalFruit(self, tree):
        bucket = {}
        re = left = 0
        for right, f in enumerate(tree):
            bucket[f] = bucket.get(f, 0) + 1
            while len(bucket) > 2:
                bucket[tree[left]] -= 1
                if bucket[tree[left]] == 0:  del bucket[tree[left]]
                left += 1
            re = max(re, right-left+1)
        return re

猜你喜欢

转载自blog.csdn.net/Sengo_GWU/article/details/86328264