5602 leetcode ,前缀和+哈希 以及滑动窗口

在这里插入图片描述

1. 前缀和+哈希

  1. 开辟Ldict 和Rdict 来记录前缀和后缀和
  2. 若key在前缀和, 并且x-key在后缀和,并且前缀和的index<后缀和 的index 则满足满足条件,记录下来比较大小
  3. 反之,key在后缀和, 并且x-key在前缀和,亦然
  4. 或者 Ldict 或者Rdict的key中有等于0的,也满足条件
class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        Ldict={}
        Rdict={}
        temp1=x
        temp2=x
        N=len(nums)
        res=N+1
        for i in range(len(nums)):
            temp1 -= nums[i]
            j=N-i-1
            temp2 -= nums[j]
            Ldict[temp1]=i
            Rdict[temp2]=j    
        for key in Ldict:
            if key ==0:
                res = min(res,Ldict[key]+1)   
            if (x-key) in Rdict and Ldict[key] < Rdict[x-key]:
                res = min(res,N-(Rdict[x-key]-Ldict[key]-1))        
        for key in Rdict:
            if key ==0:
                res = min(res,N-Rdict[key])   
            if (x-key) in Ldict and Ldict[x-key] < Rdict[key]:
                res = min(res,N-(Rdict[key]-Ldict[x-key]-1))           
        return res if res !=N+1 else -1

2. 滑动窗口解法

这个问题也可以看作是求中间最长子数组等于sum-x

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        left = 0
        N = len(nums)
        res = -1  # 这里初始化为-1吧,不要为0了! 因为res有可能为0,正好整个数组之和就是等于x,那么res要为0,才能返回N-res 等于整个数组长度
        sub=sum(nums)-x
        for i in range(N):
            sub = sub-nums[i]
            if sub==0:
                res = max(res,i-left+1)
                continue
            while sub<0 and left<=i: # 注意这里要取等号,否则整个长度正好等于x的情况就不对了
                sub += nums[left]
                if sub ==0:
                    res = max(res,i-left)
                left+=1
        print(res)        
        return N-res if res!=-1 else -1   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值