给定一个二进制数组, 计算其中最大连续1的个数。
示例 1:
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意:
输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。
相关话题:数组;
我的思路:这个是个简单题思路还是比较清晰的;对数组进行遍历,如果不是1就截断一下,存一下连续1的数量。
下面是我提交的代码;
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int index = 0;
int res = 0;
int len = nums.length;
for (int i : nums) {
if(nums[i]!=1){
res = Math.max(res,index);
index = 0;
}else{
index++;
}
}
return Math.max(res,index);
}
}
提交后看了一下别人耗时最少的,确实是比我想的多一下,也节约资源。我确实是没必要去用index去做循环的++;
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int index = -1;
int max = 0;
for(int i=0;i<nums.length;i++) {
if(nums[i] == 0) { //遇到0了,要对比下
int temp = i - 1 - index;
max = Math.max(temp, max);
index = i;
}
}
max = Math.max(max, nums.length-1-index);
return max;
}
}