79 两个整数集合A和B,求其交集

时间:2023-03-09 19:47:15
79  两个整数集合A和B,求其交集

【本文链接】

http://www.cnblogs.com/hellogiser/p/ab-intersect.html

【题目】

两个整数集合A和B,求其交集。
【分析】
1. 读取整数集合A中的整数,将读到的整数插入到map中,并将对应的值设为1。
2. 读取整数集合B中的整数,如果该整数在map中并且值为1,则将此数加入到交集当中,并将在map中的对应值改为2。通过更改map中的值,避免了将同样的值输出两次。

【代码】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
 
// 80_ABIntersect.cpp : Defines the entry point for the console application.
//

/*
version: 1.0
author: hellogiser
blog: http://www.cnblogs.com/hellogiser
date: 2014/9/26
*/

#include "stdafx.h"
#include <iostream>
#include <map>
using namespace std;

/*
1,2,3,8,9
1,1,2,3,3,10,12,15
*/
void ABIntersect(int *a, int n, int *b, int m)
{
    )
        return;
    int len = min(n, m);
    map<int, int> dict;
    int *result = new int[len];
    ;

int i;
    // for a
; i < n; i++)
    {
        dict[a[i]] = ;
    }

; i < m; i++)
    {
        )
        {
            result[cnt++] = b[i];

dict[b[i]] ++;
        }
    }

// output result
; i < cnt; i++)
    {
        cout << result[i] << " ";
    }
    cout << endl;

delete []result;
}

void test_case()
{
    };
    };
    ABIntersect(a, sizeof(a) / sizeof(int), b, sizeof(b) / sizeof(int));
}

int _tmain(int argc, _TCHAR *argv[])
{
    test_case();
    ;
}
/*
1 2 3
*/

【参考】

http://blog.****.net/zyw_ym_zone/article/details/10474443