美文网首页
2022-10-31 1658

2022-10-31 1658

作者: 木马音响积木 | 来源:发表于2022-10-30 22:48 被阅读0次

leetcode 1658 求固定值的滑动窗口的最长跨度
用左端点控制,还是右端点控制,要注意

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        tar =sum(nums) -x 
        if tar<0:return -1
        n=len(nums)
        if tar==0:return n
        #找最长的滑动窗口,窗口总和固定
        left =r =ans=he=0
        while left<n:  #这个地方最开始写了r ,
            while r<n and he<tar:
                he += nums[r]
                r+=1
            if he==tar and (t:=r-left)>ans:
                ans=t
            he-= nums[left]
            left+=1
            
        return n - ans if ans else -1


相关文章

网友评论

      本文标题:2022-10-31 1658

      本文链接:https://www.haomeiwen.com/subject/fcaltdtx.html