码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-04-06 11:32:18      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:c++   阿里巴巴   数据结构   算法   

分布式系统中的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);
}





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

标签:c++   阿里巴巴   数据结构   算法   

原文地址:http://blog.csdn.net/coder_yi_liu/article/details/44899823

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!