1. 前缀和+哈希
- 开辟Ldict 和Rdict 来记录前缀和和后缀和,
- 若key在前缀和, 并且x-key在后缀和,并且前缀和的index<后缀和 的index 则满足满足条件,记录下来比较大小
- 反之,key在后缀和, 并且x-key在前缀和,亦然
- 或者 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