zoukankan      html  css  js  c++  java
  • 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)
    {
        
    if(a == NULL || n <= 0 || b == NULL || m <= 0)
            
    return;
        
    int len = min(n, m);
        map<
    intint> dict;
        
    int *result = new int[len];
        
    int cnt = 0;

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

        
    for (i = 0; i < m; i++)
        {
            
    if (dict[b[i]] == 1)
            {
                result[cnt++] = b[i];

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

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

        
    delete []result;
    }

    void test_case()
    {
        
    int a[] = {12389};
        
    int b[] = {11233101215};
        ABIntersect(a, 
    sizeof(a) / sizeof(int), b, sizeof(b) / sizeof(int));
    }

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

    【参考】

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

  • 相关阅读:
    c# 指针unsafe/fixed -- 【一】
    Windows消息大全(转)
    Windows消息过滤
    C#预编译
    c#摄像头编程实例 (转)
    多线程按顺序执行 (转)
    定位程序集
    无需写try/catch,也能正常处理异常 (转)
    无需Try catch 的UI事件封装类
    注册表修改安全策略
  • 原文地址:https://www.cnblogs.com/hellogiser/p/ab-intersect.html
Copyright © 2011-2022 走看看