程式語言 - LeetCode - C++ - 2657. Find the Prefix Common Array of Two Arrays



題目:


解答:

class Solution {
public:
    vector<int> findThePrefixCommonArray(vector<int>& A, vector<int>& B) {
        int n = A.size();
        int comm = 0;
        vector<int> ans;
        unordered_map<int, int> mp;

        for (int i = 0; i < n; ++i) {
            mp[A[i]] += 1;
            if (mp[A[i]] == 2) {
                comm += 1;
            }

            mp[B[i]] += 1;
            if (mp[B[i]] == 2) {
                comm += 1;
            }

            ans.push_back(comm);
        }

        return ans;
    }
};