485. Max Consecutive Ones

链接

485. Max Consecutive Ones

题意

给定一个二进制数组,找出连续1的最大长度。

思路

遍历数组,当遇到1时,初始化计数器(countOne),只要不遇到1就一直累加,一旦countOne大于ans记录的最大值,则更新ans。如果遇到0则将计数器清零。遍历完成后,ans即所需答案。

代码

Java:

public class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int countOne = 0;
        int ans = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 1) {
                countOne++;
                if (countOne > ans) {
                    ans = countOne;
                }
            } else {
                countOne = 0;
            }
        }
        return ans;
    }
}

效率

Your runtime beats 85.98% of java submissions

原文地址:https://www.cnblogs.com/zyoung/p/6587172.html