leetcode with python:485. Max Consecutive Ones

题目:

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

给定一个阵列,裏头只有0跟1,找出1最多连续几次
ex:input:[1,1,0,1,1,1]=>output:3

这题遍历一次阵列就能找出答案

class Solution:    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:        cnt=0        ans=0        for i in nums:            if i:                cnt=cnt+1                ans=max(ans,cnt)            else:                cnt=0                        return ans

设置一计数器(cnt),开始遍历阵列
每遇到1,cnt就加1
遇到0,cnt就归0
回传cnt在遍历期间所达到的最大值
最后执行时间359ms(faster than 93.70%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章