1.题目描述(简单题)
给定一个二进制数组, 计算其中最大连续1的个数。
示例 1:
输入: [1,1,0,1,1,1] 输出: 3 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意:
-
- 输入的数组只包含
0
和1
。 - 输入数组的长度是正整数,且不超过 10,000。
- 输入的数组只包含
2.思路与代码
2.1 解题思路
-
- 首先,整个nums数组需要完整遍历一次,需要使用while或for循环;
- 每段连续的1的长度,需要用一个变量cnt来记录;
- 最后返回cnt中的最大值。
2.2 提交代码
class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int cnt = 0; int max_cnt = 0; /*---貌似--不支持auto关键字-----*/ //for(auto &c : nums){ //for(auto beg = nums.begin(),end = nums.end();beg != end;++beg){ //int c = *beg; int size = nums.size();//只调用一次size() for(int i = 0; i<size;++i) if(nums[i] == 1) { ++cnt; } else{ max_cnt = max(max_cnt,cnt); cnt = 0; } return max(max_cnt,cnt);//针对测试用例[1],没有机会进入else分支执行max()比较 } };
3.最大连续1的个数之二(中等题)
备注:因为这道题目前需要购买,我没有买,只是搜了一下这道扩展题,详情请点击附在末尾的原博文链接,我在这里只分析了一部分——加上附加条件“有一次将0翻转为1的机会”后,求此时最大连续1的个数。
3.1 主要题干描述
部分英文题干如下:(就是添加了附加条件——“有一次将0翻转为1的机会”)
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.
3.2 解题思路
一般地,基于基础题的扩展题的解法有两种情况:
- 大体思路和原基础题一致,只是某些局部的难点的处理要更加复杂些,因此,可以套用基础题的大体代码框架,重点思考需要突破的难点即可;
- 虽为基础题改编,但是问题发生了较大的变化,解法需要重新全盘规划。
对于本扩展题来说,因为题目本身的复杂度较低,还是比较接近第一种情况。具体解题思路:
- (1)毫无疑问,整个nums数组仍需要完整遍历一次,使用范围for语句;
- (2)需要对数字0的做进深理解:
- a.每个数字0会把它前后的字符分为两段(紧邻的两段,要么为连续的1,要么为单独的0),这两段分别有四种可能:110111(两边都是1),110011(左边为0右边为1 或 左边为1右边为0),100011(两边都是0)
- b.当选择一个0翻转为1时,它自己需要被计数,并且需要求它连接起的相邻两段的连续1的长度;
- (3)仍然使用cnt来统计每一段连续的1的长度,但是当出现0时,为了使得cnt可以继续来统计下一段连续1的长度,使用cur变量来保存刚刚统计得到的cnt值,然后cnt=0,继续开始统计;
- (4)合理放置++cnt的位置,不做if判断,可以把选中要翻转的0当作1统计入cnt中,用cur保存这个cnt值(左边段的1的长度,含翻转的0),然后cnt继续统计这个0右边的那个段中1的长度,比较 "cnt+cur"(0翻转为1后,合并起来的新的连续的1的段长) 与 max_cnt 的值,令max_cnt为两者中较大的。
3.3 完整自测代码
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int findMaxConsecutiveOnes_2(vector<int>& nums) { int cnt = 0; int cur = 0;//保存遇到当前0之前的紧邻的上一段连续1的个数;当前0的前面为0,则cur为0 /* 1110 对于第1个0,cur = 3 11100 对于第2个0,cur = 0 */ int max_cnt = 0; for (auto &c : nums) { ++cnt; if(c==0) { cur = cnt; cnt = 0; } max_cnt = max(max_cnt, cur + cnt); } return max_cnt; } }; void main() { vector<int> nums1 = { 1 }; vector<int> nums2 = { 1,1,0,1,1,1 }; vector<int> nums3 = { 1,1,0,1,0,1 }; vector<int> nums4 = { 0 }; vector<int> nums5 = { 1,1,0,1,1,1,0,1,1,1,1,1}; Solution test; cout << "输入[1] 的结果为:" << test.findMaxConsecutiveOnes_2(nums1) << endl; cout << "输入[1,1,0,1,1,1]的结果为:" << test.findMaxConsecutiveOnes_2(nums2) << endl; cout << "输入[1,1,0,1,0,1]的结果为:" << test.findMaxConsecutiveOnes_2(nums3) << endl; cout << "输入[0] 的结果为:" << test.findMaxConsecutiveOnes_2(nums4) << endl; cout << "输入[ 1,1,0,1,1,1,0,1,1,1,1,1]的结果为:" << test.findMaxConsecutiveOnes_2(nums5) << endl; }
参考资料: