485. Max Consecutive Ones
题目: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
and1
. - The length of input array is a positive integer and will not exceed 10,000
个人解法:(python)
class Solution(object): def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ count = 0 arr_result = [] for i in range(len(nums)): if nums[i] == 1: count += 1 else: if count != 0: arr_result.append(count) count = 0 if i == (len(nums)-1) and nums[i] == 1: arr_result.append(count) result = 0 for i in arr_result: if i > result: result = i return result
看了别人的解法,思路一样,python中有个比较大小的max函数,忘记用了。
应该是:
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
第一遍做,没太考虑最优解,第二遍刷题的时候在考虑。