题目:
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
链接:
3/28/2017
要细心,如果一次不对就完蛋了,比如max, sum最后一步的判断
1 public class Solution { 2 public int findMaxConsecutiveOnes(int[] nums) { 3 int max = 0, sum = 0; 4 for (int i = 0; i < nums.length; i++) { 5 if (nums[i] == 0) { 6 if (sum > max) max = sum; 7 sum = 0; 8 } else sum++; 9 } 10 return sum > max? sum: max; 11 } 12 }
有人斗法一行python
https://discuss.leetcode.com/topic/75490/one-liner/5
1 def find_max_consecutive_ones(nums) 2 nums.join.split('0').map(&:size).max || 0 3 end
更多讨论:https://discuss.leetcode.com/category/631/max-consecutive-ones