腾讯实习笔试:关于几个有序数组求交集的问题

本文探讨了如何解决多个有序数组求交集的问题,重点在于算法的时间复杂度要求。提出了两种方法:一是利用二分查找,适用于一个数组远小于另一个的情况,复杂度为n1log(n2);二是双指针遍历法,适用于数组大小相近,复杂度为o(n1+n2)。
摘要由CSDN通过智能技术生成

题目就是假设有三个有序数组对其求交集,要求算法空间复杂度必须小,有序数组量会比较大。
解法:
第一种就是用二分法查找,二分法查找的效率是log(n),两个数组求交集就是n1log(n2),当n1远小于n2的时候,这个算法效果可以
第二种就是遍历,用两个游标来实现,具体可以见代码,算法效率o(n1+n2)线性,当n1和n2比较接近时效果可以

#include<iostream>
#include<cstdlib>
#include<vector>
#include<list>
#include<algorithm>
#include<ctime>

using std::vector;
using std::list;

//获取一个大小为num,有序的数组vecInt,数组中最大的数值为 max*num
void getRandOrderIntVec(vector<int>& vecInt, int num,int max)
{
   
	vecInt.clear();
	vecInt.reserve(num);
	while (vecInt.size() < num)
	{
   
		if (vecInt.empty())
		{
   
			int value = (std::rand() % (max));
			vecInt.push_back(value);
		}
		else 
		{
   
			int value = (std::rand() % max ) + vecInt.back() + 1;
			vecInt.push_back(value);
		}
	}

}

//********************遍历法查找相同的数据**********************************
//找出三个数组中相同的数值,并且保存在vecSame的vector中
void getSameValue(vector<int>& vec1, vector<int>& vec2, vector<int>& vec3, vector<int>& vecSame)
{
   
	vecSame.clear();

	//先确定一个保存交集的空间大小
	int minNumInThreeVec = vec1.size();
	if (vec2.size() < minNumInThreeVec)
	{
   
		minNumInThreeVec = vec2.size();
	}
	if (vec3.size() < minNumInThreeVec)
	{
   
		minNumInThreeVec = vec3.size();
	}
	minNumInThreeVec /= 2; 

	vecSame.reserve(minNumInThreeVec);

	//***********************查找交集**************************
	vector<int>::iterator vecIter1 = vec1.begin();
	vector<int>::iterator vecIter2 = vec2.begin();
	vector<int>::iterator vecIter3 = vec3.begin();

	while ((vecIter1 != vec1.end())
		& (vecIter2 != vec2.end())
		& (vecIter3 != vec3.end())
		)
	{
   
		//如果相等的话
		if (
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值