LeetCode 487. Max Consecutive Ones II

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

When zero count 大于可以flip最大数目时, move walker, 每当nums[walker]等于0, zero count 减一直到zero count 等于k.

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

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

AC Java:

 1 class Solution {
 2     public int findMaxConsecutiveOnes(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return 0;
 5         }
 6         
 7         int res = 0;
 8         int count = 0;
 9         int walker = 0;
10         int runner = 0;
11         while(runner < nums.length){
12             if(nums[runner++] != 1){
13                 count++;
14             }
15             
16             while(count > 1){
17                 if(nums[walker++] != 1){
18                     count--;
19                 }
20             }
21             
22             res = Math.max(res, runner-walker);
23         }
24         
25         return res;
26     }
27 }

Follow up说input是infinite stream, 不能把整个array放在memory中.

When calculating res, can't move walker, since stream may be out of memory already.

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

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

AC Java:

 1 class Solution {
 2     public int findMaxConsecutiveOnes(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return 0;
 5         }
 6         
 7         int res = 0;
 8         int walker = 0;
 9         int runner = 0;
10         LinkedList<Integer> que = new LinkedList<>();
11         while(runner < nums.length){
12             if(nums[runner++] != 1){
13                 que.add(runner);
14             }
15             
16             while(que.size() > 1){
17                 walker = que.poll();
18             }
19             
20             res = Math.max(res, runner-walker);
21         }
22         
23         return res;
24     }
25 }

类似Longest Substring with At Most Two Distinct CharactersMax Consecutive Ones III.

posted @ 2017-01-31 08:20  Dylan_Java_NYC  阅读(666)  评论(0编辑  收藏  举报