LeetCode 485 最大连续1的个数 HERODING的LeetCode之路

给定一个二进制数组, 计算其中最大连续1的个数。

示例 1:

输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.

注意:

输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-consecutive-ones
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:
建立两个变量,一个统计最大连续1个数,一个统计当前连续1个数,遇到0更新最大连续1个数即可,当然在遍历之后,还要注意最后连续的1的个数是否比最大连续1个数大,代码如下:

class Solution {
    
    
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
    
    
        // 统计最大1的个数
        int countMax = 0;
        // 统计1的个数
        int count = 0;
        for(int i = 0; i < nums.size(); i ++) {
    
    
            // 如果是1
            if(nums[i] == 1) {
    
    
                count ++;
            } else {
    
    // 如果出现0
                countMax = max(countMax, count);
                count = 0;
            }
        }
        // 最后连续的1的个数是否大于countMax
        countMax = max(countMax, count);
        return countMax;
    }
};


/*作者:heroding
链接:https://leetcode-cn.com/problems/max-consecutive-ones/solution/zui-yi-li-jie-de-csi-lu-by-heroding-ta1l/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/113813327