小米笔试题

本文介绍了一种使用C++实现的交集与并集算法,通过遍历两个整数向量并判断元素是否存在,实现了向量之间的交集判断及合并操作。文章详细展示了如何使用STL中的find函数进行元素查找,并通过实际代码示例解释了算法的具体实现过程。

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

题一:

 

题解:

#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <cstring>
#include <deque>
#include <queue>
#include <map> 

using namespace std;


bool jiaocha(const vector<int> &vec1, const vector<int> &vec2)
{
	for(auto it = vec2.begin(); it != vec2.end(); ++it) {
		if(find(vec1.begin(), vec1.end(), *it) != vec1.end()) {
			return true;
		}
	}
	return false;
}

void merge(vector<int> &vec1, vector<int> &vec2)
{
	for(auto it = vec2.begin(); it != vec2.end(); ++it) {
		if(find(vec1.begin(), vec1.end(), *it) == vec1.end()) {
			vec1.push_back(*it);
		}
	}
}

int main()
{
    int n, num;
	string s;
	cin >> n;
	getline(cin, s);
	vector<vector<int>> vec(n);
	for(auto row = vec.begin(); row != vec.end(); ++row) {
		getline(cin, s);		
		istringstream ss(s);
		while(ss >> num) {
			row->push_back(num);
		}
	} 
	
	for(auto row = vec.begin(); row != vec.end(); ++row) {
		for(auto row2 = vec.begin(); row2 != vec.end(); ++row2) {
			if(row == row2)	continue;
			bool bf = jiaocha(*row, *row2);
			if(bf) {
				merge(*row, *row2);
				row2 = vec.erase(row2);
				--row2;
			}
		}
	}
	
	int maxlen = 0;
	for(auto row = vec.begin(); row != vec.end(); ++row) {
		if(row->size() > maxlen) {
			maxlen = row->size();
		}
	}
	cout << vec.size() << endl << maxlen << endl;
    return 0;
}

  

转载于:https://www.cnblogs.com/xzxl/p/9713327.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值