leetcode: 485. The maximum number of consecutive 1s (44 ms, 32.6 MB)

leetcode: 485. Maximum number of consecutive 1s

The topic is as follows:

Given a binary array, count the maximum number of consecutive 1s in it.

Example:

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

prompt:

The input array only contains 0 and 1. The length of the input array is a positive integer and does not exceed 10,000.

Analysis : First of all, Likou does not need your input and output, and it does not need your parameters. They are all prepared for you, at least for this question.

Question analysis , I believe everyone can understand the question. It
is to calculate the number of 1s in the time that the number of consecutive output 1s is the most.

The code is actually very simple, because I am Xiaobai, so I can only solve problems violently .

Code explanation:
1. When inputting 1, count will automatically increase by one

2. When the input is not 1, there are two cases

  • The first is to update the value of max when count is greater than the value of max

  • The second is if it is not greater than, then the max value will not change

  • After the first or second type of operation is over, change the value of count to 0 and let him start over again until he enters 1 again.

But note that if the last input 1 is the column with the most, the code at this time does not run to the update count operation

Therefore, we need to perform trinocular operations on this when we return , that is, if the last count is greater than max, we output count, otherwise, if the last count is smaller than max, we still output max

class Solution {
    
    
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
    
      
 
		int count = 0,max = 0;
		for (int i = 0; i < nums.size(); i++) {
    
    
			if (nums[i] == 1) {
    
    
				count++;
			}
			else {
    
    
                if(count>max){
    
    
                    max = count;
                }
                count = 0;
                }
			
		}
        return (count>max)?count:max;

    }
};

However, this code is a waste of time, and the running speed is not good. If there is a better code, please post it in the comment area and discuss it together. After all, it is the first time to write a force button, more or less low

Guess you like

Origin blog.csdn.net/weixin_42198265/article/details/114504400