【LeetCode】485.Max Consecutive Ones_EASY(九)

来源:互联网 发布:wind数据库试用账号 编辑:程序博客网 时间:2024/06/18 01:28

485.Max Consecutive Ones

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

思路:设连续1的个数为number,遍历数组
数组元素为1时:
1.不是数组最后一个元素时,number++;
2.是数组最后一个元素时,number++,然后进行add操作。
数组元素为0时:
进行add操作,然后将number设为0。
最后返回List的最大值即可。

代码:

public class Solution {    public int findMaxConsecutiveOnes(int[] nums) {        List<Integer> conse = new ArrayList<Integer>();        int number=0;        for(int i=0;i<nums.length;i++){            if(nums[i]==1){                if(i==nums.length-1){                    number++;                    conse.add(number);                }else number++;            }else{                conse.add(number);                number=0;            }        }        return Collections.max(conse);    }}

完成。

0 0
原创粉丝点击