485. Max Consecutive Ones

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 and 1.
The length of input array is a positive integer and will not exceed 10,000

  • 题目的意思就是给定一个只有0和1的数组,并且假定这个数组的的长度是一个不超过10000的正整数,要求最长的1的个数

题目比较简单就直接贴代码了

public class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        //一个计数器记录1的个数
        int k = 0;
        //表示最大的1的个数
        int max = 0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==1){
                k++;
                if(k>max)
                    max = k;
            }
            else
                //如果出现了0,就将k置0重新计数
                k = 0;
        }
        return max;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容