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,设置一个计数器,如果数组中的元素为1的计数器自增,然后将计数器的值赋值给连续1末尾的数组值。如果数组中的元素等于0的话,计数器清0,继续循环判断。最后判断数组中的最大值就是最大连续1的个数。
缺点:时间复杂度过长,每次要遍历2遍数组。
public int findMaxConsecutiveOnes(int[] nums) {
int length = nums.length;
int count = 0;
int max = nums[0];
for (int i = 0; i <= length - 1; i++) {
if (nums[i] == 1) {
count++;
nums[i] = count;
} else if (nums[i] == 0) {
count = 0;
continue;
}
}
for (int j = 0; j <= length - 1; j++) {
if (nums[j] > max) {
max = nums[j];
}
}
return max;
}
优化解法
Java中提供判断最大值的函数,Math.max(a,b),直接使用;不用自己遍历数组寻找最大值。
public int findMaxConsecutiveOnes(int[] nums) {
int result = 0;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
count++;
result = Math.max(count, result);
}
else count = 0;
}
return result;
}
}