Given a binary array, find the maximum number of consecutive 1s in this array.
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.
原题地址: Max Consecutive Ones
难度: Easy
题意: 找出连续为1的子数组的最大长度
思路1:
因为只有0, 1,可以通过确定0的位置确定1的长度.但需要考虑边界问题,可以假设 -1位置 和 len(nums) 位置都为0,边界问题就可以解决了
索引: 0 1 2 3 4 5 6
数值: 1 1 1 1 0 1 1
变为:
索引: -1 0 1 2 3 4 5 6 7 数值: 0 1 1 1 1 0 1 1 0
第一组连续1的子数组长度: 4 - (-1) - 1 = 4
第二组连续1的子数组长度: 7 - (4) - 1 = 2
代码:
class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ j = -1 # 初始化0的位置 res = 0 for i in range(len(nums)): if nums[i] == 0: res = max(res, i-j-1) j = i res = max(res, len(nums)-j-1) return res
思路2:
遍历数组,统计1的个数
代码:
class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ res = 0 count = 0 for i in range(len(nums)): if nums[i] == 1: count += 1 res = res if res > count else count else: count = 0 return res
时间复杂度: O(n)
空间复杂度: O(1)