leetcode1004
Posted AsenYang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1004相关的知识,希望对你有一定的参考价值。
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的起止坐标。然后滑动窗口,进行比较,保留最大值。
以上是关于leetcode1004的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 1004. Max Consecutive Ones III
[滑动窗口] leetcode 1004 Max Consecutive Ones III
滑动窗口7:Leetcode 1004. 最大连续1的个数 III
leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段