给定一个二进制数组 nums
, 计算其中最大连续 1
的个数。
示例 1:
输入:nums = [1,1,0,1,1,1] 输出:3 解释:开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3.
示例 2:
输入:nums = [1,0,1,1,0,1] 输出:2
提示:
1 <= nums.length <= 10^5
nums[i]
不是0
就是1
.
提示 1
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
解法1:一次遍历
Java版:
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int ans = 0;
int count = 0;
int n = nums.length;
for (int i = 0; i < n; i++) {
if (nums[i] == 0) {
ans = Math.max(ans, count);
count = 0;
} else if (nums[i] == 1) {
count++;
ans = Math.max(ans, count);
}
}
return ans;
}
}
复杂度分析
-
时间复杂度:O(n),其中 n 是数组的长度。需要遍历数组一次。
-
空间复杂度:O(1)。
Python3版:
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
ans = 0
count = 0
for i in range(len(nums)):
if nums[i] == 0:
ans = max(ans, count)
count = 0
else:
count = count + 1
ans = max(ans, count)
return ans
复杂度分析
-
时间复杂度:O(n),其中 n 是数组的长度。需要遍历数组一次。
-
空间复杂度:O(1)。