首页 > 其他 > 详细

LeetCode Max Consecutive Ones II

时间:2017-01-31 10:35:08      阅读:524      评论:0      收藏:0      [点我收藏+]

原题链接在这里: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 }

 

LeetCode Max Consecutive Ones II

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/6358630.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!