找2个数组中相同的数

原创、转载请注明出处

input:

[1,2,3,5,7,5]

[2,4,5,8,7]

output:

[2,5,7]

 

思路:有重复元素,想到用set,set又有排序功能,2个有序的set找相同个数列,直接2个指针遍历一遍,时间复杂度是O(n);

 

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


int main()
{
    set<int>A, B;

    string str;
    getline(cin, str);
    stringstream s(str);
    char c;
    while (s >> c)
    {
        if (c != '[' && c != ']' && c != ',')
        {
            int tmp = c - '0';
            A.insert(tmp);
        }
    }
    

    string str1;
    getline(cin, str1);
    stringstream s1(str1);
    while (s1 >> c)
    {
        if (c != '[' && c != ']' && c != ',')
        {
            int tmp = c - '0';
            B.insert(tmp);
        }
    }


    set<int>::iterator pA = A.begin();
    set<int>::iterator pB = B.begin();


    while (pA != A.end() && pB != B.end())
    {
        while (pB != B.end() && *pB < *pA)
        {
            pB++;
        }
        if (pB != B.end() && *pA == *pB)
        {
            cout << *pA << ' ';
        }
        pA++;
    }
}

 

 

posted @ 2018-04-20 07:46  哲贤  阅读(499)  评论(0编辑  收藏  举报