【题目描述】
给定一个二进制数组 nums
, 计算其中最大连续 1
的个数。
https://leetcode.cn/problems/max-consecutive-ones/
【示例】
【代码】admin
package com.company;
// 2022-01-20
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int max = 0;
for(int num: nums){
if (num == 1){
count++;
}else {
max = Math.max(count, max);
count = 0;
}
}
max = Math.max(count, max);
System.out.println(max);
return max;
}
}
public class Test {
public static void main(String[] args) {
new Solution().findMaxConsecutiveOnes(new int[]{1,1,0,1,1,1}); // 输出: 3
new Solution().findMaxConsecutiveOnes(new int[]{1,0,1,1,0,1}); // 输出: 2
}
}
【代码】简单
package com.company;
// 2022-01-20
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int max = 0;
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == 1){
count++;
}else {
count = 0;
}
max = Math.max(max, count);
}
System.out.println(max);
return max;
}
}
public class Test {
public static void main(String[] args) {
new Solution().findMaxConsecutiveOnes(new int[]{1,1,0,1,1,1}); // 输出: 3
new Solution().findMaxConsecutiveOnes(new int[]{1,0,1,1,0,1}); // 输出: 2
}
}
【代码】双指针
package com.company;
// 2022-01-20
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int l = 0;
int r = 0;
int n = nums.length;
int res = 0;
while (r < n){
// 获取 连续1的最远下标
while (r < n && nums[r] != 0) r++;
// 始终是r - l的差为最大连续的1
res = Math.max(res, r - l);
// 获取 连续0的最远下标, 此时到到1则停止
while (r < n && nums[r] != 1) r++;
// 将新的1的位置赋值给l 然后接着统计1最长的小标
l = r;
}
System.out.println(res);
return res;
}
}
public class Test {
public static void main(String[] args) {
new Solution().findMaxConsecutiveOnes(new int[]{1,1,0,1,1,1}); // 输出: 3
new Solution().findMaxConsecutiveOnes(new int[]{1,0,1,1,0,1}); // 输出: 2
}
}