【Code】关关的刷题日记21——Leetcode 485. Max Consecutive Ones

时间:2022-05-07
本文章向大家介绍【Code】关关的刷题日记21——Leetcode 485. Max Consecutive Ones,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关小刷刷题 21——Leetcode 485. Max Consecutive Ones

题目

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:

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

题目的意思是一个数组中只包含0和1,让我们找出最长的连续1的个数。

思路

思路:遍历一遍该数组,统计连续1出现的次数count,每次遇到0之后,就开始重新计数,在这个过程中不断选取较大的count来更新最终结果re。时间复杂度O(n).

class Solution {public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int count=0, re=0;
        for(int x:nums)
        {
            if(x==1)
                count++;
            else
            {
                re=max(count,re);
                count=0;
            }
        }
        return max(re,count);
    }};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。