【LeetCode 简单题】113-最大连续1的个数

声明:

今天是第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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值