`

查找两个有序数组的交集(C++实现)

 
阅读更多
// Type your C++ code and click the "Run Code" button!
// Your code output will be shown on the left.
// Click on the "Show input" button to enter input data to be read (from stdin).

#include <iostream>
#include <vector>
using namespace std;

// find the intersection of two array
vector<int> intersect(vector<int> a, vector<int> b) {
    vector<int> intersection;
    vector<int>::iterator ai = a.begin();
    vector<int>::iterator bi = b.begin();
    while(ai != a.end() && bi != b.end()) {
        if(*ai > *bi) {
            bi ++;
        } else if(*ai < *bi) {
            ai ++;
        } else {
            intersection.push_back(*ai);
            ai ++;
            bi ++;
        }
    }
    return intersection;
}

void print_vector(vector<int> vet) {
    for(vector<int>::iterator iter = vet.begin(); iter != vet.end(); iter++) {
        cout<<*iter<<" ";
    }
    cout<<endl;
}

int main() {
    // test data
    vector<int> alist;
    vector<int> blist;
    for(int i = 0; i < 100; i+=3) alist.push_back(i);
    for(int i = 0; i < 100; i+=2) blist.push_back(i);
    cout<<"alist: "<<endl;
    print_vector(alist);
    cout<<"blist: "<<endl;
    print_vector(blist);
    cout<<"intersection: "<<endl;
    print_vector(intersect(alist, blist));
    
    return 0;
}

 

欢迎关注微信公众号——计算机视觉:

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics