Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Intersection of Two Arrays ใน C++

แนวคิด

สมมติว่ามีอาร์เรย์สองอาร์เรย์ ให้หาจุดตัดของทั้งสอง

เช่น ถ้าอินพุตคือ [1,5,3,6,9],[2,8,9,6,7] ผลลัพธ์คือ [9,6]

วิธีแก้:

  • กำหนด map mp1, mp2
  • กำหนดอาร์เรย์ res
  • สำหรับ x ใน nums1: เพิ่ม mp1[x] ขึ้น 1
  • สำหรับ x ใน nums2: เพิ่ม mp2[x] ขึ้น 1
  • สำหรับคู่ key-value แต่ละคู่ x ใน mp1: cnt := 0, cnt := min ของค่า x และ mp2[key of x], ถ้า cnt > 0: แทรก key of x ลงท้าย res
  • คืนค่า res

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v) {
    cout << "[";
    for(int i = 0; i<v.size(); i++) {
        cout << v[i] << ", ";
    }
    cout << "]"<<endl;
}
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2){
        unordered_map<int, int> mp1, mp2;
        vector<int> res;
        for (auto x : nums1) mp1[x]++;
        for (auto x : nums2) mp2[x]++;
        for (auto x : mp1) {
            int cnt = 0;
            cnt = min(x.second, mp2[x.first]);
            if (cnt > 0) res.push_back(x.first);
        }
        return res;
    }
};
main() {
    Solution ob;
    vector<int> v = {1,5,3,6,9}, v1 = {2,8,9,6,7};
    print_vector(ob.intersection(v, v1));
}

อินพุต

{1,5,3,6,9},{2,8,9,6,7}

เอาต์พุต

[9, 6, ]