485. Max Consecutive Ones最长的连续1的个数

时间:2023-03-09 19:50:28
485. Max Consecutive Ones最长的连续1的个数

[抄题]:

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.

[暴力解法]:

用temp,result,结果发现写起来很麻烦

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

还是局部最大值+全局最大值的思路。用三元表达式解决局部变量的连续和中断问题

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 是maxHere + 1 统计,不是n + 1,这是是乐至?

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

用三元表达式解决局部变量的连续和中断问题

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

487. Max Consecutive Ones II 好像不是数学就是两根指针吧

[LC给出的题目变变变]:

[代码风格] :

class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
//cc
if (nums == null || nums.length == 0) {
return 0;
} //ini
int max = 0;
int maxHere = 0; //for loop
for (int n : nums) {
max = Math.max(max, maxHere = n == 0 ? 0 : maxHere + 1);
} //return
return max;
}
}