LeetCode Max Consecutive Ones II

本文介绍了解决LeetCode上最长连续1子串问题的方法,通过使用快慢指针技巧,实现高效查找。同时也讨论了输入为无限流的情况,并提供Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/max-consecutive-ones-ii/

题目:

Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0.

Example 1:

Input: [1,0,1,1,0]
Output: 4
Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
    After flipping, the maximum number of consecutive 1s is 4.

Note:

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

Follow up:
What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?

题解:

Max Consecutive Ones进阶题目.

用快慢指针. 每当nums[runner]是0时, zero count 加一. 当 zero count 大于可以flip最大数目k时, 开始移动walker, 每当nums[walker]等于0, zero count 减一直到zero count 等于k.

同时维护最大值res = Math.max(res, runner-walker+1).

Time Complexity: O(nums.length). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int findMaxConsecutiveOnes(int[] nums) {
 3         int res = 0;
 4         int zero = 0;
 5         int k = 1;
 6         
 7         for(int walker = 0, runner = 0; runner<nums.length; runner++){
 8             if(nums[runner] == 0){
 9                 zero++;
10             }
11             while(zero > k){
12                 if(nums[walker++] == 0){
13                     zero--;
14                 }
15             }
16             res = Math.max(res, runner-walker+1);
17         }
18 
19         return res;
20     }
21 }

Follow up说input是infinite stream, 不能把整个array放在memory中. 看上面的代码知道,maintain 最大值时,其实需要的是index.

可以只用queue来记录等于0的index即可. 当queue.size() > k表示0的数目超过了可以flip的最大值,所以要dequeue.

Time Complexity: O(n). Space: O(k).

AC Java:

 1 public class Solution {
 2     public int findMaxConsecutiveOnes(int[] nums) {
 3         int res = 0;
 4         int k = 1;
 5         LinkedList<Integer> que = new LinkedList<Integer>();
 6         for(int walker = 0, runner = 0; runner<nums.length; runner++){
 7             if(nums[runner] == 0){
 8                 que.offer(runner);
 9             }
10             while(que.size()>k){
11                 walker = que.poll()+1;
12             }
13             res = Math.max(res, runner-walker+1);
14         }
15         return res;
16     }
17 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6358630.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值