题目链接:
力扣https://leetcode-cn.com/problems/max-consecutive-ones/
【分析】简单模拟题,注意判断更新最大值的时机就行。
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int n = nums.length, ans = -1, i, t = 0;
for(i = 0; i < n; i++){
if(nums[i] == 1) t++;
else{
ans = Math.max(ans, t);
t = 0;
}
}
return Math.max(ans, t);
}
}
【方法二 滑动窗口】设置滑动窗口的左右端点,如果右端点处为1,则右端点继续右滑,否则更新最大值以及左端点到当前右端点。
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int right = 0, left = 0, ans = 0, n = nums.length;
while(right < n){
if(nums[right] == 1){
right++;
}else{
ans = Math.max(ans, right - left);
right++;
left = right;
}
}
return Math.max(ans, right - left);
}
}
【Python版】
class Solution:
def findMaxConsecutiveOnes(self, nums) -> int:
ans, t = 0, 0
for i in nums:
if i == 1:
t += 1
else:
ans = max(ans, t)
t = 0
return max(ans, t)
class Solution:
def findMaxConsecutiveOnes(self, nums) -> int:
left, right, ans = 0, 0, 0
n = len(nums)
while right < n:
if nums[right] == 0:
ans = max(ans, right - left)
right += 1
left = right
else:
right += 1
return max(ans, right - left)