求两个数组的交集

方法:先用A创建 有序二叉树,然后用B中的数值依次在二叉树中寻找,如果找到了,就增加到交集数组中

复杂度:创建二叉树的复杂度logn,在二叉树中查找的复杂度是 logn*(m+1)

 #include"stdio.h"
int commonArray[20];
int com_len=0;
struct node
{
	int data;
	struct node *lNode;
	struct node *rNode;
};
struct node *head;
void printTree(struct node *p)
{
	if(p)
	{
		printTree(p->lNode );
		printf("%d  ",p->data );
		printTree(p->rNode );
	}
}
struct node *createTree(int a[],int len)
{
	struct node *curNode,*nextNode,*newNode;
	int i=1;
	if(len<=0)
		return NULL;
	head=(struct node *)malloc(sizeof(struct node *));
	head->data =a[0];
	head->lNode =NULL;
	head->rNode =NULL;
	while(i<len)
	{
		newNode=(struct node *)malloc(sizeof(struct node *));
		newNode->data =a[i];
		newNode->lNode =NULL;
		newNode->rNode =NULL;

		curNode=head;
		if(head->data>a[i])
			nextNode=head->lNode ;
		else nextNode=head->rNode ;

		while(nextNode)
		{
			curNode=nextNode;
			if(curNode->data >a[i])
				nextNode=curNode->lNode ;
			else
				nextNode=curNode->rNode ;
		}

		if(curNode->data >a[i])
			curNode->lNode =newNode;
		else
			curNode->rNode =newNode;
		i++;
	}
	return head;
	
};
int findValueInTree(struct node *p,int value)
{
	int findValue=0;
	if(p)
	{
		if(p->data ==value)
			findValue=1;
		else if(p->data >value)
			findValue=findValueInTree(p->lNode ,value);
		else 
			findValue=findValueInTree(p->rNode ,value);
	}
	return findValue;
}
//打印数组
void printArray(int *a,int len)
{
	int i=0;
	if(len<=0)
		return;
	for(;i<len;i++)
		printf("%d  ",a[i]);
	printf("\n");
}
void findCommonArray(int *a,int a_len,int *b,int b_len)
{
	int j=0;
	head=createTree(a,a_len);//创建二叉树
    for(;j<b_len;j++)
	{
      if(findValueInTree(head,b[j]))
		  commonArray[com_len++]=b[j];
	}
	printf("打印第一个数组\n");
	printArray(a,a_len);
	printf("打印第二个数组\n");
	printArray(b,b_len);
	printf("打印二个数字的交集\n");
	printArray(commonArray,com_len);
//	printTree(head);
}

int main()
{
	int a[10]={5,0,8,7,9,6,33,22,30,88
	};
	int b[8]={0,-11,12,65,98,77,5,30
	};
	findCommonArray(a,10,b,8);
	getchar();
	return 0;
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值