13-求交集

链接:https://www.nowcoder.net/acm/contest/76/C
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述

给你两个升序排列的集合,求出两个集合的交集。

输入描述:

有多个测试用例,输入到文件结束。
对于每一个测试用例:
第一行输入两个整数n,m(0<n,m<=1000000),分别代表第一个集合和第二个集合的元素的数量。
第二行输入n个整数,表示第一个集合中的元素,元素之间用空格隔开。
第三行输入m个整数,表示第二个集合中的元素,元素之间用空格隔开。
两个集合中的元素范围在[-1000000000,1000000000]区间内。

输出描述:

每个测试用例用一行来输出两个集合的交集的所有元素(元素用空格隔开且按升序排列),若交集为空则输出"empty"。
示例1

输入

2 3
1 3
1 2 3

输出

1 3

备注:

交集为空的情况下,输出"empty"
1.用set超内存!!!
#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
using namespace std;
set <int> myset;

int main(){
	int n, m, x, flag = 0;
	while(scanf("%d%d", &n, &m) == 2){
		flag = 0;
		for(int i = 0; i < n; i++){
			scanf("%d", &x);
			myset.insert(x);
		}
		for(int i = 0; i < m; i++){
			scanf("%d", &x);
			if(myset.count(x)){
				flag = 1;
				printf("%d ", x);
			}
		}
		if(flag == 0){
			printf("empty
");
		}
		else{
			printf("
");
		}
		myset.clear();
	}
	return 0;
}

  2.爆力就行:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int a[1000001];
int b[1000001];

int main(){
	int n, m;
	while(scanf("%d%d", &n, &m) == 2){
		for(int i = 0; i < n; i++)
			scanf("%d", &a[i]);
		for(int j = 0; j < m; j++)
			scanf("%d", &b[j]);
		int ca = 0, cb = 0, ct = 0, flag = 0;
		while(ca < n && cb < m){
			if(a[ca] == b[cb]){
				if(flag){
					printf(" ");
				}
				printf("%d", a[ca]);
				flag = 1;
				ca++;
				cb++;
			}
			else if(a[ca] < b[cb]){
				ca++;
			}
			else{
				cb++;
			}
		}
		if(flag){
			printf("
");
		}
		else{
			printf("empty
");
		}
	}
	
	return 0;
}

  



原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/8442893.html