[LeetCode] [Array] Question number: 485, the maximum number of consecutive 1

every blog every motto: You will never know unless you try

0. Preface

Nonsense: I played leetcode sporadically a long time ago, but there is no way to talk about it. This time I just want to use C++ to do something, so I can just brush the questions.
Summary:
This series of blogs mainly records the road to Leetcode. The idea has been around for a long time and has not been started (including this article). If you have an idea, you should do it immediately. After a long time, you will lose the original strength.


Description:

  • In order to better grasp the essence of the question, and to avoid the previous chaotic phenomenon of "one hammer in the east and one stick in the west", this time the title is categorized.
  • Attach the questions to be brushed before each category
  • I've been busy recently, and I may not be so fast in rewriting questions.
  • This time, the purpose of brushing the question is to pursue the completion , that is, to record the author's general solution, which may not be optimal.

Note: Language: c++


This time the title is array:

Insert picture description here

1. Text

1.1 Title

Topic: Given a binary array, calculate the maximum number of consecutive 1s.
Example:
Input: [1,1,0,1,1,1]
Output: 3

1.2 Solution

class Solution {
    
    
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
    
    

        int max = 0; // 最大连续1的个数
        int count = 0; // 记录连续1的个数

        for(size_t i = 0;i<nums.size();i++)
        {
    
       
            
            if(nums[i]==1) // 
            {
    
    
                count++;
                // 比较大小
                max = (max>count)?max:count;
            }
            else
            {
    
       
                count = 0; // 如果不连续,count归零
            }
        }
        return max;
    }
};

1.3 Submit results

Insert picture description here

Note: The code is similar to the code of a subject in the comment area, but my time and space consumption are relatively large.

references

[1] https://leetcode-cn.com/problems/max-consecutive-ones/
[2] https://leetcode-cn.com/circle/article/48kq9d/

Guess you like

Origin blog.csdn.net/weixin_39190382/article/details/108456834