s4553711
3/31/2017 - 4:31 PM

leetcode-349

leetcode-349

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
vector<int> intersection(vector<int>& n1, vector<int>& n2) {
    vector<int> result;
    sort(n1.begin(), n1.end());
    sort(n2.begin(), n2.end());
    int i = 0, j = 0;
    while ( i < n1.size() && j < n2.size()) {
        if (n1[i] < n2[j]) {
            i++;
        } else if (n1[i] > n2[j]) {
            j++;
        } else {
            if (result.size() == 0 || result.back() != n1[i]) {
                result.push_back(n1[i]);
            }
            i++;
            j++;
        }   
    }   
    return result;
}

int main() {
    int foo [5] = { 16, 2, 77, 40, 12071 };
    int bar [7] = { 1, 2, 37, 40, 71, 23, 16 };
    vector<int> v(foo, foo + 1);
    vector<int> v2(bar, bar + 1);
    vector<int> v3 = intersection(v, v2);
    for (auto a : v3) {
        cout << a << endl;
    }   
}