Max Consecutive Ones

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

求解思路:

要找到一个二进制数组中连续1的 最大数量,

num0:之前连续1的最大数目

num1:当前正在判断的块中连续1的最大数量

采用for循环,对于array[i],

array[i]=1,num1++;

array[i]!=1,num0=max(num0,num1);num1=0;

最后输出max(num0,num1)即为连续1最大个数。

算法的复杂度为O(n)。

程序运行的结果如下:


完整的代码如下:

#include<cstdlib>
#include<iostream>
#define maxnum 10000
using namespace std;


class vector
{
public:
	int len;
	int *arr;
	vector(){};
	~vector(){};

	void malloc();//对数组赋值
	void free();//释放内存
	int findMaxConsecutiveOnes();//找出连续1的最大数量
};

void vector::malloc()
{
	int i,p;
	len=0;
	arr=new int[maxnum]; 
	i=0;
	while(cin>>arr[i]&&arr[i]!='p')//输入用空格隔开,以输入p为结束
	{
		
		if(arr[i]!=0&&arr[i]!=1)
		{
			cout<<"the input is wrong!";
			exit(1);
		}

		i++;
	}
	len=i;
}

void vector::free()
{
	delete []arr;
}

int vector::findMaxConsecutiveOnes()
{
	int i,s=0,t=0;
	for(i=0;i<len;i++)
	{
		if(arr[i]==1)
			t++;
		else
		{
			s=(s>t)?s:t;
			t=0;
		}
	}
	s=(s>t)?s:t;
	return s;
}


int main()
{
	int t;
	vector nums;
	cout<<"please input the array which only contains 0 and 1\n ";
	cout<<"end up with p\n";
	nums.malloc();
	t=nums.findMaxConsecutiveOnes();
	cout<<t;
	nums.free();
	return 0;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值