485. Max Consecutive Ones

本文介绍了一种在二进制数组中查找最长连续1序列的方法。通过计算数组中1的总数,可以快速确定是否存在连续的1序列,并找到最长的连续1序列的长度。这种方法适用于需要高效处理二进制数据的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

思路:

1,求数组的和

2,若和为0,则不存在1,返回0

3,若和为1,则只有一个1,返回1

4,有两个或两个以上的1,则设置一个两个变量,分别表示每段连续的1的长度和最长的长度

 

 

#pragma once
#include<iostream>
#include<vector>
#include<numeric>

using namespace std;


class Solution {
public:
	int findMaxConsecutiveOnes(vector<int>& nums) {
		//求和
		int sum = accumulate(nums.begin(), nums.end(),0);
		//若和为0,则没有1
		if (sum == 0)
		{
			return 0;
		}
		//如果和为1,则只有一个1
		if (sum == 1)
		{
			return 1;
		}
		//否则有两个及以上的1,则判断是否连续
		int leng = nums.size();
		int one = 0;//1的个数
		int onesum = 0;//1的最长序列的个数
		for (int i = 0; i < nums.size(); i++)
		{
			if (nums[i] == 1)
			{
				//如果是1,则计数
				one += 1;
				if (one > onesum)
				{
					onesum = one;
				}
			}
			else
			{
				one = 0;
			}
		}
		return onesum;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值