宝典练习2之求两个数组的交集

来源:互联网 发布:获取httppost请求数据 编辑:程序博客网 时间:2024/06/05 03:48

分析问题:

1,最容易想到的是暴力枚举法,即拿A数组中的元素一个个去B数组中遍历,有相等的即为交集元素,假设A数组长为m,B数组为n,那时间代价为O(mn)!

2,一种有预处理的方法:

先对两个数组进行排序处理,一般代价为O(n)到O(logn)了。然后对两个已经有序的数组求交集。

对两个数组分别设置下标i,j,从零开始遍历,若碰到相等的,i和j同时加1,该元素并入交集,若A【i】大于B【j】那么A【i】得从B数组j以上去查找,即j++;同理另一种情况为i++。时间代价为O(m+n)!

下边为简易代码:

#include "stdafx.h"#include <iostream>using namespace std;int mixed(int *a, int *b, int length1, int length2, int *mix){if (a == NULL || b == NULL || length1 == 0 || length2 == 0){return -1;}int i = 0, j = 0;int count = 0;while (i < length1 && j < length2){if (a[i] == b[j]){mix[count++] = a[i];i++;j++;}elseif (a[i] < a[j]){i++;}elsej++;}return count;}int _tmain(int argc, _TCHAR* argv[]){int a[] = {1,3,5,7,9};int b[] = {2,4,5,7,10,12};int *mix = new int[sizeof(a)/sizeof(a[0])];int count = mixed(a, b, sizeof(a)/sizeof(a[0]), sizeof(b)/sizeof(b[0]), mix);for (int i = 0; i < count; i++){cout << mix[i] << ' ';}cout << endl;system("pause");return 0;}
3,另一种思想是把两个数组都遍历到一个新的数组里,采用计数排序的方法,统计重复的数字即为交集元素,前提是两个数组中的数据范围不能太大。时间代价应为O(m+n)!

4,采用哈希表的思想:

将数组A哈希到哈希表中,然后对数组B中的元素在哈希表中查找,找到了即为交集元素。

时间代价为o(m)或者o(n)。

但是有额外的空间代价为o(n)或者o(m)。

1 0
原创粉丝点击