您的位置:首页 > 其它

【LeetCode】485.Max Consecutive Ones_EASY(九)

2017-04-08 05:47 495 查看
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);
}
}


完成。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: