算法笔记: 力扣#485 最大连续1的个数

问题描述


解法


分析

Python 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class :
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
n = 0
for num in nums:
if num == 1:
n += 1
else:
ans = max(n, ans)
n = 0
return max(n, ans)

Java 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class {
public int findMaxConsecutiveOnes(int[] nums) {
int ans = 0;
int n = 0;
for(int num : nums){
if(num == 1){
n ++;
}else{
ans = ans > n ? ans : n;
n = 0;
}
}
return ans > n ? ans : n;
}
}

时间复杂度

O(N).

空间复杂度

O(1).

链接


485. Max Consecutive Ones
485. 最大连续1的个数
(English version) Algorithm Notes: Leetcode#485 Max Consecutive Ones