找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++;
    }
}

 

 

转载于:https://www.cnblogs.com/mu-ye/p/8887990.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值