寻找两个升序数组里的共同值

来源:互联网 发布:淘宝上匡威正品店 编辑:程序博客网 时间:2024/06/03 16:01
// MicrosoftInterviewProblem.cpp : Defines the entry point for the console application.//两个含有n个元素的有序(非降序)整型数组a和b(数组a与b中都没有重复元素),求出其共同元素,//a = 0, 1, 2, 3, 4//b = 1, 3, 5, 7, 9//那么它们的交集为{ 1, 3 }。#include "stdafx.h"#include <iostream>#include <stdlib.h>#include <vector>using namespace std;void FindTheSame(vector<int>&a, vector<int>&b, vector<int>&c){    int asize = a.size();    int bsize = b.size();    int aptr, bptr;    aptr = bptr = 0;    while (aptr < asize&&bptr < bsize)    {        if (a[aptr] == b[bptr])        {            c.push_back(a[aptr]);            aptr++;            bptr++;        }        else if (a[aptr] < b[bptr])            aptr++;        else            bptr++;    }}int main(){    vector<int>a;    vector<int>b;    vector<int>c;    int temp;    cout << "please input the vector a and b in no decrease sequence! -1 stop the input" << endl;    cout << "a: ";    while (1)    {        cin >> temp;        if (temp == -1)            break;        a.push_back(temp);    }    cout << "b: ";    while (1)    {        cin >> temp;        if (temp == -1)            break;        b.push_back(temp);    }    FindTheSame(a, b, c);    cout << "The same is : " ;    for (auto it = c.begin(); it != c.end(); it++)        cout << " " << *it;    system("pause");    return 0;}
2 0