LeetCode485(力扣485)最大连续1的个数 C++ 使用C++11for

485 最大连续1的个数

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

示例 1:

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

注意:

输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。
我提交的代码
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int max_count = 0;
        int temp = 0;
        for (auto i : nums) {
            if (i == 1) {
                temp++;
            }
            else {
                temp = 0;
            }
            if (temp > max_count) max_count = temp;
        }
        return max_count;
    }
};

LeetCode485(力扣485)最大连续1的个数 C++ 使用C++11for_第1张图片

我的思想

呀,这个题不是遍历一遍数组就好了吗?既然要在原来的数组中查值,使用C++11的for循环爽的不行呀!

我的代码优化
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int max_count = 0;
        int temp = 0;
        for (auto i : nums) {
            if (i == 1) {
                temp++;
            }
            else {
                temp = 0;
            }
            max_count = max(temp,max_count);       //<---------------------
        }
        return max_count;
    }
};

LeetCode485(力扣485)最大连续1的个数 C++ 使用C++11for_第2张图片

将if判断改成了使用max函数,速度蹭蹭蹭往上提呀!

你可能感兴趣的:(Leetcode笔记,#,数组,c++,算法,leetcode)