1 class Solution: 2 def getMax(self,B:'List[int]'): 3 n = len(B) 4 maxlen = 0 5 curlen = 0 6 for i in range (n): 7 if B[i] == 1: 8 curlen += 1 9 else: 10 maxlen = max(maxlen,curlen) 11 curlen = 0 12 return max(maxlen,curlen) 13 def longestOnes(self, A: 'List[int]', K: int) -> int: 14 if K == 0: 15 return self.getMax(A) 16 n = len(A) 17 zlist = list() 18 for i in range(n): 19 if A[i] == 0: 20 zlist.append(i) 21 if len(zlist)<=K: 22 return n 23 maxlen = 0 24 for zi in range(len(zlist)-K+1): 25 ti = zi+K 26 27 left = 0 28 right = len(A)-1 29 if zi==0: 30 left = zlist[zi] 31 else: 32 left = zlist[zi-1]+1 33 if zi == len(zlist)-K: 34 right = len(A) - 1 35 else: 36 right = zlist[ti] - 1 37 38 maxlen = max(maxlen, right - left +1) 39 40 return maxlen
经过了几次尝试,终于作出来了。主要的思路是滑动窗口:
先记录所有的0的索引,然后选择等K宽的窗口,计算窗口“所连接”的连续1的起止坐标。然后滑动窗口,进行比较,保留最大值。