原题是 :
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.
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
思路是 :
用一个变量num来记录1的个数,遇到0时num归0;用另一个变量ans来记录最大的nums,注意最后一步也要再取一次最大,否则只是遇到0才取最大,如果最长1序列出现在末尾,会疏忽最后一步对ans最大取值的更新。
代码是:
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num,ans = 0,0
for i in xrange(len(nums)):
if nums[i] == 1:
num = num + 1
elif nums[i] == 0:
ans = max(num,ans)
num = 0
ans = max(num,ans)
return ans
借鉴别人的代码
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
cnt = 0
ans = 0
for num in nums:
if num == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans
一个是循环变量的设置比我的简单,另外在遇到1的时候就更新最大值,避免了最后出现问题的可能性。