Leetcode_Array -- 485. Max Consecutive Ones [easy]

Given a binary array, find the maximum number of consecutive 1s in this array.

给定一个二进制数组(只包含0,1),找到连续出现1最大的子数组,求其长度。

Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.

Note:

  1. The input array will only contain 0 and 1.
  2. The length of input array is a positive integer and will not exceed 10,000

Solutions:

Python

(1)
'''
这个是遍历数组的方法,统计连续的1的个数,设置一个最大值maxlength,
并用length这个临时长度更新maxlength,当length > maxlength时对
maxlength进行更新
'''
class Solution:
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = 0
        maxlength = 0
        for num in nums:
            if num == 1:   #元素为1时统计length
                length +=1
            else:   #进入else说明num为0,那么length必须置0,且length>maxlength时更新maxlength
                if length >maxlength:
                    maxlength = length
                length = 0
        if length>maxlength:   #这个时为了预防全部为1的情况,全部为1时不会进入上面判断的else中
            maxlength = length
        return maxlength

(2)
'''
下面的两个方法思想是一样的,先将nums变换成可以调用split函数的形式,
再用split('0')的模式将nums分开,nums此时变成一个含有1的数组,统计
这个数组中最大的长度,其实就是连续的1最大的长度
(2)是将nums变成了二进制的表示形式
(3)是将nums中先变换成字符串,然后split,在变换成list,再统计
'''
class Solution:
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        tmp = bytearray(nums).split(b'\x00')
        return max([len(l) for l in tmp])
(3)
class Solution:
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        temp = list(map(str,nums))   #将nums中元素变成字符串类型
        temp = ''.join(temp).split('0')   #将list变成字符串后用'0'进行切分
        length = list(map(len,temp))   #length中存储连续'1'字符串的长度
        return max(length)   #返回最大的长度即可
C++

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int curlength = 0;
        int maxlength = 0;
        for (int i : nums){
            if (i == 1){
                curlength += 1;
            }
            else{
                if (curlength>maxlength){
                    maxlength = curlength;
                }
                curlength = 0;
            }
        }
        if (curlength > maxlength){
            maxlength = curlength;
        }
        return maxlength;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值