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
问题描述: 给定一个二进制数组,计算1连续出现的最多次数
我的思路:定义两个变量,一个counter 记录出现次数,一个temp 记录当前出现次数, 如果遇0则temp归零重新计数。同时考虑边界情况
public int FindMaxConsecutiveOnes(int[] nums) { if(nums.Length == 0) return 0; int counter = 0; int temp = 0; for(int i = 0; i < nums.Length; i++){ if(nums[i] == 1) { temp++; }else { if(temp > counter) { counter = temp; } temp = 0; } } if(temp > counter) { counter = temp; } return counter; }