[Leetcode] 487. Max Consecutive Ones II 解题报告
来源:互联网 发布:浏览器缺少java插件 编辑:程序博客网 时间:2024/06/10 16:17
题目:
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: 4Explanation: 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
and1
. - 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?
思路:
由于可以允许翻转一次0,所以我们记录两部分内容:zeroLeft表示在需要翻转的0之前的连续1的个数,zeroRight表示在需要翻转的0之后的连续1的个数。一旦我们遇到一个0,就需要更新zeroLeft和zeroRight了。最终只要记录下来zeroLeft + zeroRight的最大值即可。注意到这里我们让zeroRight同时包含了需要翻转的0,这样就可以统一处理只有一个0的情况了。算法的时间复杂度是O(n),空间复杂度是O(1)。由于我们不需要对原来出现的数据进行重新存取,所以这个代码也满足了Follow up的要求,可以处理无限长的数据流。
代码:
class Solution {public: int findMaxConsecutiveOnes(vector<int>& nums) { int maxConsecutive = 0, zeroLeft = 0, zeroRight = 0; for (int i = 0; i < nums.size(); ++i) { ++zeroRight; if (nums[i] == 0) { zeroLeft = zeroRight; zeroRight = 0; } maxConsecutive = max(maxConsecutive, zeroLeft + zeroRight); } return maxConsecutive; }};
阅读全文
0 0
- [Leetcode] 487. Max Consecutive Ones II 解题报告
- 【LeetCode】Max Consecutive Ones 解题报告
- 【LeetCode】485.Max Consecutive Ones解题报告
- [Leetcode] 485. Max Consecutive Ones 解题报告
- LeetCode 487. Max Consecutive Ones II
- Leetcode 485. Max Consecutive Ones 最大连续1 解题报告
- 487. Max Consecutive Ones II
- LEETCODE--Max Consecutive Ones
- LeetCode: Max Consecutive Ones
- 【leetcode】Max Consecutive Ones
- LeetCode:Max Consecutive Ones
- LeetCode Max Consecutive Ones
- LeetCode Max Consecutive Ones
- leetCode-Max Consecutive Ones
- LeetCode 485. Max Consecutive Ones
- 【Leetcode】485. Max Consecutive Ones
- LeetCode 485. Max Consecutive Ones
- [LeetCode]485 Max Consecutive Ones
- redis基础
- %00截断问题
- 输入多个半径,求面积、周长
- [ 莫队 树状数组 ] [ AHOI2013 ] BZOJ3236
- 【排序】冒泡排序
- [Leetcode] 487. Max Consecutive Ones II 解题报告
- Ubuntu17.04安装QQ和微信
- try...catch...finally和throws
- Yaml介绍及JYaml将数据写入yaml文件
- 杭code1008
- 7.1 分析并写出下面程序的运行结果
- Python安装
- 理解java的三大特性之多态
- struts.xml配置文件中自动提示配置