原题链接在这里: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:
0
and 1
.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