leetcode1004

时间:2024-11-07 13:07:26
 class Solution:
def getMax(self,B:'List[int]'):
n = len(B)
maxlen = 0
curlen = 0
for i in range (n):
if B[i] == 1:
curlen += 1
else:
maxlen = max(maxlen,curlen)
curlen = 0
return max(maxlen,curlen)
def longestOnes(self, A: 'List[int]', K: int) -> int:
if K == 0:
return self.getMax(A)
n = len(A)
zlist = list()
for i in range(n):
if A[i] == 0:
zlist.append(i)
if len(zlist)<=K:
return n
maxlen = 0
for zi in range(len(zlist)-K+1):
ti = zi+K left = 0
right = len(A)-1
if zi==0:
left = zlist[zi]
else:
left = zlist[zi-1]+1
if zi == len(zlist)-K:
right = len(A) - 1
else:
right = zlist[ti] - 1 maxlen = max(maxlen, right - left +1) return maxlen

经过了几次尝试,终于作出来了。主要的思路是滑动窗口:

先记录所有的0的索引,然后选择等K宽的窗口,计算窗口“所连接”的连续1的起止坐标。然后滑动窗口,进行比较,保留最大值。