您的位置:首页 > 其它

【每日一题】2012.5.26:输入两个数组中相同的元素

2012-05-27 09:49 260 查看
第一题:两个数组,大小自定,无序

#include <iostream>
#include <set>
using namespace std;

const int N = 20;
const int M = 10;

void fun(int a[],int b[])
{
	set<int> num;
	set<int> result;
	for(int i=0; i != M; ++i)
	{
		num.insert(a[i]);
	}
	for(int j=0; j != N; ++j)
	{
		if(num.count(b[j]))
		{
			result.insert(b[j]);
		}
	}
	for(set<int>::iterator b = result.begin(); b != result.end(); ++b)
	{
		cout << *b <<endl;
	}
}

int main(int argc,char **argv)
{
	int a[] = {35,26,54,2,4,6,9,8,10,-1};
	int b[] = {54,4,3,1,29,88,-2,35,8,9,100,81,79,26,1,555,-33,2,2,6};
	fun(a,b);
	return 0;
}




第二题,如果两个数组都是非递减的



//如果两个数组是非递减的
#include <iostream>
using namespace std;

const int N = 5;
const int M = 10;

void fun(int a[],int b[])
{
	int i=0;
	int j=0;
	while(j != M && i != N)
	{
		if(a[i] > b[j])
		{
			j++;
		}
		else if(a[i] < b[j])
		{
			i++;
		}
		else
		{
			cout << a[i] <<endl;
			int temp = a[i];
			i++;
			while(temp == a[i])
			{
				i++;
				if(i >= N)
				{
					break;
				}
			}
			j++;
			while(temp == b[j])
			{
				j++;
				if(j >= M)
				{
					break;
				}
			}
		}
	}
}

void main()
{
	int a[] = {2,2,3,4,5};
	int b[] = {2,2,3,3,3,3,4,12,13,14};
	fun(a,b);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐