声明:
今天是第113道题。给定一个二进制数组, 计算其中最大连续1的个数。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除
(手动比心ღ( ´・ᴗ・` ))
正文
题目:给定一个二进制数组, 计算其中最大连续1的个数。
示例 1:
输入: [1,1,0,1,1,1] 输出: 3 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.注意:
- 输入的数组只包含
0
和1
。- 输入数组的长度是正整数,且不超过 10,000。
解法1。遍历nums,遇1就count加1,反之把count放到res中,然后置0,在循环结束后还需手动添加count到res中,因为全1的情况就不会走else分支,所以需要手动添加,代码如下。
执行用时: 52 ms, 在Max Consecutive Ones的Python提交中击败了98.67% 的用户
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = []
count = 0
for i in nums:
if i == 1:
count += 1
else:
res.append(count)
count = 0
res.append(count) # 避免全1的情况,在上述代码中未能append计算出的count
return max(res)
# 还有种方法可以省去在循环结束后还append(count)
在开始的地方添加一句nums.append(0),这样可以保证在for循环中至少走一次else分支
解法2。其实上述代码用了多余的空间,其实不必要存储所有count的取值,简化成只保留最大的count,代码如下。
执行用时: 52 ms, 在Max Consecutive Ones的Python提交中击败了98.67% 的用户
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_con = 0 # 存储最大的count计数
count = 0
for i in nums:
if i == 1:
count += 1
else:
if count>max_con:
max_con = count
count = 0
if max_con < count:
max_con = count
return max_con
解法3。发现一种很聪明的做法,利用了nums元素的0、1这2种取值,代码如下。
执行用时: 56 ms, 在Max Consecutive Ones的Python提交中击败了87.17% 的用户
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
sum_1 = 0
for i in nums:
sum_1 = sum_1*i + i
if sum_1 > res:
res = sum_1
return res
结尾
解法1:原创
解法2&解法3:LeetCode