LeetCode-485连续最大1的个数-Max-Consecutive-Onespython-java

6次阅读

共计 961 个字符,预计需要花费 3 分钟才能阅读完成。

公众号:爱写 bug

给定一个二进制数组,计算其中最大连续 1 的个数。

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

示例 1:

输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续 1,所以最大连续 1 的个数是 3.

注意:

  • 输入的数组只包含 01
  • 输入数组的长度是正整数,且不超过 10,000。

Note:

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

解题思路:

​ 记录一个指针向右移动,用一个数记录 1 的个数,遇 1 就累加 1,遇 0 就倒置为 0。具体见 Java 注释。

Java:

class Solution{public int findMaxConsecutiveOnes(int[] nums) {
        int temp=0,count=0;//temp 记录当前连续 1 的个数,count 记录当前最大连续 1 的个数
        for (int i=0;i<nums.length;i++){// 指针右移
            if(nums[i]==1){temp++;// 遇 1 累加 1}else{if(count<temp){count=temp;// 记录目前最大连续 1 的个数}
                temp=0;// 遇 0 倒置为 0
            }
        }
        return (count>temp)? count:temp;// 返回 count、temp 中较大的数
    }
}

注意:

​ 返回值必须是 counttemp 中较大的一个。明明已经比较了counttemp,并把较大的赋值给count,很明显是count 更大,为什么还要比较?

​ 这是因为还有一种输入数组全为 1 的情况,此时 temp 一直累加,从未遇到 0,所以 count 自始至终都不可能得到 temp 的值。

python3:

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        count=temp=0
        for num in nums:
            if num==1:
                temp+=1
            else:
                if(count<temp):
                    count=temp
                temp=0
        return count if count>temp else temp

正文完
 0