leetcode刷题笔记-two pointer

1695. Maximum Erasure Value

class Solution:
    def maximumUniqueSubarray(self, nums: List[int]) -> int:
        re = left = total = 0
        seen = set()
        for n in nums:
            if n not in seen:
                total += n
                re = max(re, total)
                seen.add(n)
            else:
                while nums[left] != n:
                    seen.remove(nums[left])
                    total -= nums[left]
                    left += 1
                # nums[left] = n
                left += 1
        return re


2563. Count the Number of Fair Pairs

class Solution:
    def countFairPairs(self, nums, lower, upper):
        # two pointers, return the count of pairs
        # find all the paris that sum <= upper, X
        # find all the paris that < lower, Y
        # TOTAL = x-y
        nums.sort()
        total = i = 0
        j = len(nums) - 1
        while i < j:
            if nums[i] + nums[j] > upper:
                j -= 1
            else:
                total += j - i
                i += 1

        i, j = 0, len(nums) - 1
        while i < j:
            if nums[i] + nums[j] > lower - 1:
                j -= 1
            else:
                total -= j - i
                i += 1
        return total

1712. Ways to Split Array Into Three Subarrays

class Solution:
    def waysToSplit(self, nums: List[int]) -> int:
        # O(n) as j, k can only keep going to right like i
        preS = []
        total = re = 0
        for n in nums:
            total += n
            preS.append(total)

        j = k = 0
        n = len(nums)
        # i is the end of left subarray
        # j is the min end of mid subarray
        # k is the max end of mid subarray
        for i in range(n-2):
            while j <= i or j < (n-1) and (preS[j] - preS[i]) < preS[i]:  # middle < left
                j += 1
            
            while k < j or k < (n-1) and (preS[k] - preS[i]) <= (total - preS[k]):  # middle <= right
                k += 1
            k -= 1
            re = (re + k - j+1) 

        return re % (10**9+7)

2149. Rearrange Array Elements by Sign

class Solution:
    def rearrangeArray(self, nums: List[int]) -> List[int]:
        # 间隔的必须是正数变成负数
        # 原本的同符号的数字,顺序不变
        p1, p2 = 0, 1 
        re = [0] * len(nums)
        for n in nums:
            if n > 0:
                re[p1] = n
                p1 += 2
            else:
                re[p2] = n
                p2 += 2
        return re 

1477. Find Two Non-overlapping Sub-arrays Each With Target Sum

class Solution:
    def minSumOfLengths(self, arr: List[int], t: int) -> int:
        '''
        sliding windows to find all valid subArray 
        use array minLength to store the length of the shortest valid subArray till/before cur position i
        
        give an valid subArrary with left, right position, 
        cur length + minLength[left-1] is a candicate answer
        '''
        sub = l = 0
        minLength = [0] * len (arr)  # record the length of shortest valid subArray till cur position i
        smallest = 0  # the length of shortest valid subArray till cur position
        re = 0
        for i, v in enumerate(arr): 
            sub += v
            while sub >= t:
                length = i - l + 1
                if sub == t:
                    smallest = min(smallest, length) if smallest else length
                    minLength[i] = min(minLength[i], length) if minLength[i] else length       
                    # 
                    if l > 0 and minLength[l-1]:
                        re = min(length+minLength[l-1], re) if re else length + minLength[l-1]
                    
                sub -= arr[l]
                l += 1
            
            if smallest:
                minLength[i] = smallest
        return re if re else -1

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值