Given a binary array, find the maximum number of consecutive 1s in this array.
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.
寻找每一次中第一次出现的0和第一次出现的1,注意在找到0后要跳出这个位置,不然会死循环。
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int maxlen =0;
int pos =0 ;
while(pos<nums.length&&nums[pos]==0)
pos++;
// first 1 ;
while(pos<nums.length)
{
int start = pos;
while(pos<nums.length&&nums[pos]==1)
pos++;
// fisrt 0
int end = pos;
int len = end -start ;
pos++;
if(len>maxlen)
maxlen=len;
}
return maxlen;
}
}
网友评论