c++之数组篇2:计算两个有序数组的交集



#include <iostream>
//using namespace std;

int mixed(int arr1[],int n1,int arr2[],int n2,int* mix )
{
	int i = 0;
	int j = 0;
	int k = 0;
	//mix = new int[n1];
	while (i < n1 && j < n2)
	{
		if(arr1[i] == arr2[j])
		{
			mix[k++] = arr1[i];
			//k++;
			i++;
			j++;
		}
		else if (arr1[i]>arr2[j])
			j++;
		else if (arr1[i]<arr2[j])
			i++;
	}
	return k;
}
int main()
{	
	int *m  = NULL; //存储相同元素的指针
	int num;//存储两个数组相同元素个数
	int a[] = {0,1,2,3,4};
	int b[] = {1,3,5,7,9};
	int len1 = sizeof(a)/sizeof(a[0]);
	int len2 = sizeof(b)/sizeof(b[0]);
	m = new int[len1];
	num = mixed(a,len1,b,len2,m);
	printf("两数组相同元素个数:	%d\n",num);
	printf("相同元素为:\n");
	for(int i = 0;i < num;i++)
		printf("%d",m[i]);

	return 0;
}


阅读更多
换一批

没有更多推荐了,返回首页