0485. 最大连续 1 的个数 #40
utterances-bot
started this conversation in
Comments
Replies: 3 comments 1 reply
-
#滑动窗口 class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
fast, slow = 0, 0 #从索引为0的位置开始
n = len(nums)
# 用ans记录最大连续1的长度
ans = 0
while fast < n:
if nums[fast] == 0: #如果fast为0,则slow和fast同时前进,直到都指向1
fast += 1
slow = fast
elif nums[slow] == nums[fast] == 1: #如果fast和slow都是1,则slow停止,而fast向前直到fast指向0
fast += 1
ans = max(ans, fast-slow) #更新ans
return ans |
Beta Was this translation helpful? Give feedback.
0 replies
-
# 比较另类
def findMaxConsecutiveOnes(nums):
s = ''.join(map(str, nums)).split('0')
max = 0
for i in s:
if max < len(i):
max = len(i)
return max |
Beta Was this translation helpful? Give feedback.
1 reply
-
#小白手搓,看结果好像比这个快一点,不知道有没有参考意义 class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
SumList = []
Sum = 0
Len = len(nums)
for i in range (Len):
Sum+=nums[i]
if(nums[i] ==0):
if(Sum != 0):
SumList.append(Sum)
Sum = 0
if(i == Len-1 and Sum!=0):
SumList.append(Sum)
if(len(SumList)==0):
return 0
else:
return max(SumList) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
0485. 最大连续 1 的个数 | 算法通关手册
https://algo.itcharge.cn/Solutions/0400-0499/max-consecutive-ones/
Beta Was this translation helpful? Give feedback.
All reactions