第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定

LeetCode 485:連續(xù)最大1的個數(shù) Max Consecutive Ones(python java)

標(biāo)簽:
Java Python

公众号:爱写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
點(diǎn)擊查看更多內(nèi)容
TA 點(diǎn)贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學(xué)習(xí),寫下你的評論
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊有機(jī)會得

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號

舉報(bào)

0/150
提交
取消