Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [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.
My idea:for循环遍历,最后退出循环的时候也要判断,因为为1的时候我不能去给max赋值
class Solution: def findMaxConsecutiveOnes(self, nums): count=0 max=0 for i in nums[::]: if(i==1): count=count+1 if(i==0): if(max<count): max=count count=0 if (max < count): max = count return max
那用双指针怎么做呢,参考一下别人的,主要就是从slow开始数,fast往前跑,跑完一个循环给slow,就这样迭代
class Solution { public int findMaxConsecutiveOnes(int[] nums) { int max = 0; int slow = 0; int fast = 0; int end = nums.length; while (slow < end) { fast = slow; int count = 0; while (fast < end && nums[fast++] == 1) { count++; } max = Math.max(max,count); slow = fast; } return max; } }
ok 我试着用pyhton写一遍
class Solution: def findMaxConsecutiveOnes(self, nums): m = 0 a = 0 b = 0 end = len(nums) while (a < end): b = a count = 0 while (nums[b] == 1): count = count + 1 b = b + 1 if(b==end): break m = max(m, count) a = b return m
ok,超出时间限制555