17-最大连续1的个数

image-20210427200820859

自己的做法

算法思想

使用两个变量max和current,max用来存当前已访问过的元素中最大连续1的个数,current表示当前正在访问的连续1的最大个数。

如果当前元素不为1或者遍历结束,就和max比较,将较大值赋给max即可。

算法实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int max = 0, current = 0;
int length = nums.size();
for(int i = 0; i < length; i++) {
if(nums[i] == 1) {
current++;
} else {
max = max < current ? current : max;
current = 0;
}
}
max = max < current ? current : max;
return max;
}
};

性能分析

时间复杂度:遍历数组,O(n)O(n)

空间复杂度:O(1)O(1)

官方给出的解法一样。


17-最大连续1的个数
https://zhaoquaner.github.io/2022/05/11/leetcode/数组/17-最大连续1的个数/
更新于
2022年5月22日
许可协议