美文网首页
485. Max Consecutive Ones

485. Max Consecutive Ones

作者: namelessEcho | 来源:发表于2017-09-22 21:11 被阅读0次

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;
    }
}

相关文章

网友评论

      本文标题:485. Max Consecutive Ones

      本文链接:https://www.haomeiwen.com/subject/qbqqextx.html