我正在try 解决LeetCode问题1493. Longest Subarray of 1's After Deleting One Element:
给出一个二进制数组
nums
,您应该从中删除一个元素.返回the size of the longest non-empty subarray containing only
1
's in the resulting array.返回0
如果没有这样的子array.
思维过程
在数组的开头应用i
和j
的滑动窗机制:
- 如果
array[j]
不是0,我们将继续递增j
,因为 - 如果
array[j]
是0,这是第一次,我们仍然增加j
,因为它是安全的,并增加count0
- 如果
array[j]
是0并且是第二次0,如果array[i]
是0,那么我们减少计数并增加i
- 如果
array[j]
是0,并且是第二次0,如果array[i]
不是0,那么我们只需增加i
我的代码
class Solution:
def longestSubarrayOf1s(self, array):
i,j = 0,0
N = len(array)
toReturn,count0,curr_count=0,0,0
while j < N:
if array[j] == 1:
j+=1
else:
if count0 == 0:
j+=1
count0+=1
else:
if array[i] == 0:
i+=1
count0-=1
else:
i+=1
print('i am updating my max answer to ', j-i, 'in the window of ', i, j)
toReturn = max(toReturn, j-i)
return toReturn
测试数组
[1,1,1] #expected 2
[1,1,0,1] #expected 3
[0,1,1,1,0,1,1,0,1] #expected 5
问题
我的代码没有返回任何正确的答案.对于上面列出的三个测试用例,它返回3、4和6.
我的错误是什么?