Max Consecutive Ones
2017-09-19 11:48
281 查看
Q:
原文链接:https://discuss.leetcode.com/topic/75445/java-clean-solution-easily-extensible-to-flipping-k-zero-and-follow-up-handled/2
The idea is to keep a window
The following solution does not handle follow-up, because
previous input stream
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.
原文链接:https://discuss.leetcode.com/topic/75445/java-clean-solution-easily-extensible-to-flipping-k-zero-and-follow-up-handled/2
The idea is to keep a window
[l, h]that contains at most
kzero
The following solution does not handle follow-up, because
nums[l]will need to access
previous input stream
Time: O(n) Space: O(1)
public int findMaxConsecutiveOnes(int[] nums) { int max = 0, zero = 0, k = 1; // flip at most k zero for (int l = 0, h = 0; h < nums.length; h++) { if (nums[h] == 0) zero++; while (zero > k) if (nums[l++] == 0) zero--; max = Math.max(max, h - l + 1); } return max; }
Now let's deal with follow-up, we need to store up to k
indexes of zero within the window [l, h]so that we know where to move
lnext when the window contains more than
kzero. If the input stream is infinite, then the output could be extremely large because there could be super long consecutive ones. In that case we can use
BigIntegerfor all indexes. For simplicity, here we will use
int
Time: O(n) Space: O(k)public int findMaxConsecutiveOnes(int[] nums) { [/code]
[/code]int max = 0, k = 1; // flip at most k zero Queue<Integer> zeroIndex = new LinkedList<>(); for (int l = 0, h = 0; h < nums.length; h++) { if (nums[h] == 0) zeroIndex.offer(h); if (zeroIndex.size() > k) l = zeroIndex.poll() + 1; max = Math.max(max, h - l + 1); } return max; }Note that setting
k = 0will give a solution to the earlier version Max Consecutive OnesFor
k = 1we can apply the same idea to simplify the solution. Here
qstores the index of zero within the window
[l, h]so its role is similar to
Queuein the above solution
public int findMaxConsecutiveOnes(int[] nums) { int max = 0, q = -1; for (int l = 0, h = 0; h < nums.length; h++) { if (nums[h] == 0) { l = q + 1; q = h; } max = Math.max(max, h - l + 1); } return max; }
相关文章推荐
- Array-Max Consecutive Ones
- 【Leetcode】485. Max Consecutive Ones
- leetcode-485-Max Consecutive Ones
- Leetcode_Array_Max Consecutive Ones
- Max Consecutive Ones
- leetcode解题报告(14):Max Consecutive Ones
- LeetCode 485. Max Consecutive Ones
- Leetcode:485. Max Consecutive Ones 找二进制串连续1最多是多少
- Leetcode 485. Max Consecutive Ones
- LeetCode 485 Max Consecutive Ones
- LeetCode 485. Max Consecutive Ones
- leetcode oj java 485. Max Consecutive Ones
- 485. Max Consecutive Ones [LeetCode]
- [Array]485. Max Consecutive Ones
- LeetCode485:Max Consecutive Ones 解答
- 485. Max Consecutive Ones
- leetcode 485 Max Consecutive Ones
- [LeetCode] Max Consecutive Ones 最大连续1的个数
- [LeetCode]485. Max Consecutive Ones
- leetcode485~Max Consecutive Ones