美文网首页LeetCode笔记
LeetCode笔记:485. Max Consecutive

LeetCode笔记:485. Max Consecutive

作者: Cloudox_ | 来源:发表于2018-01-17 09:16 被阅读29次

    问题(Easy):

    Given a binary array, find the maximum number of consecutive 1s in this array.

    Example 1:
    Input: [1,1,0,1,1,1]
    Output: 3
    Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.

    Note:

    1. The input array will only contain 0 and 1.
    2. The length of input array is a positive integer and will not exceed 10,000

    大意:

    给出一个二进制数组,在数组中找到连续的1最大的长度。

    例1:
    输入:[1,1,0,1,1,1]
    输出:3
    解释:开头两个数字和最后三个数字是连续的1。
    最大的连续的1是3个。

    注意:

    1. 输入的数组只包含0和1。
    2. 输入数组的长度是个正整数且不超过10000。

    思路:

    无非就是遍历数组,检查连续的1,用一个临时变量记录每次连续的1的个数,连续结束时判断是否比最大的连续个数要大。

    代码的写法可以有很多种,也会随着写法不同带来一些效率差异,但时间复杂度是一样的。

    代码(C++):

    class Solution {
    public:
        int findMaxConsecutiveOnes(vector<int>& nums) {
            int res = 0;
            int temp = 0;
            bool flag = true;
            for (int i = 0; i < nums.size(); i++) {
                if (nums[i] == 1) {
                    if (flag) temp++;
                    else {
                        temp = 1;
                        flag = true;
                    }
                    if (temp > res) res = temp;
                } else 
                    if (flag) flag = false;
            }
            return res;
        }
    };
    

    合集:https://github.com/Cloudox/LeetCode-Record


    查看作者首页

    相关文章

      网友评论

        本文标题:LeetCode笔记:485. Max Consecutive

        本文链接:https://www.haomeiwen.com/subject/qlsyoxtx.html