自学内容网 自学内容网

485. Max Consecutive Ones

Given a binary array nums, return the maximum number of consecutive 1’s in the array.

Example 1:

Input: nums = [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.

Example 2:

Input: nums = [1,0,1,1,0,1]
Output: 2

Constraints:

1 <= nums.length <= 105
nums[i] is either 0 or 1.

https://leetcode.cn/problems/max-consecutive-ones/description/

思路一:数组中只有0和1求连续1的长度,求出连续1的和就是连续1的长度,直接用前缀和,加一个条件遇到0跳过就好了

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        n=len(nums)
        for i  in  range(1,n):
            if nums[i]==0:
                continue
            nums[i]=nums[i-1]+nums[i]
        return max( nums )

思路二:初始化两个ret、count两个int类型的变量。

  1. count用于记录在数组中某一段连续1的数量
  2. 当这段1遇到0时,此时我们ret = max(ret,count)比较,将ret更新为更大的连续1数量
  3. count重置为0 ,然后开启下一次循环
  4. 这里要注意下,如果数组以1结果会导致缺失最后一次比较,所以在结尾需要在进行一次比较操作即可。PS: Python可以给数组append一个0,避免4操作。
class Solution:
    def findMaxConsecutiveOnes(self, nums):
        ret = count = 0
        nums.append(0)
        for i in nums:
            if i == 1:
                count += 1
            else:
                ret = max(ret, count)
                count = 0
        return ret

原文地址:https://blog.csdn.net/weixin_44245188/article/details/142326663

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!