阿里巴巴面试题,rpc请求保序接收算法

在分布式系统中,解决RPC请求乱序问题,设计一个算法确保序列保序输出。例如,对于序列(1, 2, 5, 8, 10, 4, 3, 6, 9, 7),正确输出为1-10的有序序列。算法需高效且健壮,同时需要编写单元测试进行验证。" 97044628,7645409,Elasticsearch集群配置与管理,"['Elasticsearch集群', '分布式搜索', '数据存储', '索引管理', '高可用性']

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

分布式系统中的RPC请求经常出现乱序的情况。

写一个算法来将一个乱序的序列保序输出。例如,假设起始序号是1,对于(1, 2, 5, 8, 10, 4, 3, 6, 9, 7)这个序列,输出是:

1

2

3, 4, 5

6

7, 8, 9, 10

 

上述例子中,3到来的时候会发现4,5已经在了。因此将已经满足顺序的整个序列(3, 4, 5)输出为一行。

 

要求:

1. 写一个高效的算法完成上述功能,实现要尽可能的健壮、易于维护

2. 为该算法设计并实现单元测试


#include <iostream>
#include <set>
#include <stdlib.h>
using namespace std;

void out_by_order(int input[], int n)
{
	set<int> id_set;
	int m = 1;
	for(int i = 0; i < n; i++)
	{
		if(input[i] == m)
		{
			cout<<m;
			id_set.erase(m);
			while(1)
			{
				if(id_set.find(++m) != id_set.end())
				{
					cout<<','<<m;
				}
				else
				{
					cout<<endl;
					break;
				}
			}
		}
		else
		{
			id_set.insert(input[i]);
		}
	}
}

void test(int a[], int n)
{
	srand(time(NULL));
	set<int> t;
	for(int i = 0; i < n; i++)
	{
		while(1)
		{
			int rand_id = rand() % n + 1;
			if(t.find(rand_id) == t.end())
			{
				a[i] = rand_id;
				t.insert(a[i]);
				break;
			}
		}
	}
	cout<<"input:(";
	for(int j = 0; j < n; j++)
	{
		if(j == n-1)
		{
			cout<<a[j];
		}
		else
		{
			cout<<a[j]<<',';
		}
	}
	cout<<")"<<endl;
	out_by_order(a, 10);
}

int main(int agrc, char *argv[])
{
	int a[10] = {1, 2, 5, 8, 10, 4, 3, 6, 9, 7};
	out_by_order(a, 10);
	cout<<endl;
	cout<<"test"<<endl;

	test(a, 10);
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值