485 Max Consecutive Ones

来源:互联网 发布:java mail 附件 io 编辑:程序博客网 时间:2024/06/06 02:23

485 Max Consecutive Ones
求连续的1的个数
第一个想到的老办法,用两个指针:start来记录开始与结束

class Solution(object):    def findMaxConsecutiveOnes(self, nums):        """        :type nums: List[int]        :rtype: int        """        start,answer=0,0        while start<len(nums):            if not nums[start]:#如果是零                start+=1            else:                end=start+1                while end<len(nums)  and nums[end]:                    end+=1                answer=max(answer,end-start)                start=end+1        return answer

discuss有个更好的方法:
我们无需使用两个指针,只需要记录当前1的个数,如果遇到0,则把计数重置为0

class Solution(object):    def findMaxConsecutiveOnes(self, nums):        """        :type nums: List[int]        :rtype: int        """        count,answer=0,0        for x in nums:            if x==1:                count+=1                answer=max(answer,count)            else:                count=0        return answer
0 0
原创粉丝点击