Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Intersection of Two Arrays trong C++


Cho hai mảng, tìm giao của chúng (các phần tử xuất hiện trong cả hai, mỗi phần tử chỉ lấy một lần).

Ví dụ: [1,5,3,6,9] và [2,8,9,6,7] → [9,6].

Giải thuật

  1. Dùng unordered_set cho mảng 1.
  2. Duyệt mảng 2, nếu phần tử có trong set 1 thì thêm vào kết quả và xóa khỏi set (tránh trùng).

Ví dụ triển khai C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> set1(nums1.begin(), nums1.end());
        vector<int> res;
        for (int x : nums2) {
            if (set1.count(x)) {
                res.push_back(x);
                set1.erase(x);
            }
        }
        return res;
    }
};

void print(vector<int> v) {
    cout << "[";
    for (int i = 0; i < v.size(); i++) cout << v[i] << (i+1

Đầu vào / Đầu ra

Input: {1,5,3,6,9}, {2,8,9,6,7}
Output: [9, 6]