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:
- The input array will only contain
0
and1
. - 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;
}
};