LeetCode 2657. Find the Prefix Common Array of Two Arrays

🔗 https://leetcode.com/problems/find-the-prefix-common-array-of-two-arrays

题目

  • 给两个数组 A 和 B,是 n 的全排列
  • 返回数组 C,表示在 index 及之前,A 和 B 有多少个相同的数

思路

  • hashset ,遍历 index,判断此时 A 和 B 的共同数字有几个
  • frequency 统计,遍历 index,A index 和 B index 的 frequency++,若 frequency 为 2,则计数

代码

cpp 复制代码
class Solution {
public:
    vector<int> solution1(vector<int>& A, vector<int>& B) {
        unordered_set<int> s;
        vector<int> C(A.size());
        for (int i = 0; i < A.size(); i++) {
            s.insert(A[i]);
            for (int j = 0; j <= i; j++) {
                if (s.count(B[j])) C[i]++;
            }
        }
        return C;
    }

    vector<int> solution2(vector<int>& A, vector<int>& B) {
        unordered_map<int, int> m;
        vector<int> C(A.size());
        for (int i = 0; i < A.size(); i++) {
            m[A[i]]++;
            m[B[i]]++;
            if (i != 0) C[i] = C[i-1];
            if (m[A[i]] == 2) C[i]++;
            if (A[i] == B[i]) continue;
            if (m[B[i]] == 2) C[i]++;
        }
        return C;
    }
    vector<int> findThePrefixCommonArray(vector<int>& A, vector<int>& B) {
        //return solution1(A, B);
        return solution2(A, B);
        
        
    }
};
相关推荐
不忘不弃9 分钟前
指针元素的使用
算法
he___H11 分钟前
滑动窗口一题
java·数据结构·算法·滑动窗口
AI科技星12 分钟前
统一场论质量定义方程:数学验证与应用分析
开发语言·数据结构·经验分享·线性代数·算法
ULTRA??14 分钟前
KD-Tree的查询原理
python·算法
jianfeng_zhu33 分钟前
不带头节点的链式存储实现链栈
数据结构·算法
lightqjx35 分钟前
【算法】双指针
c++·算法·leetcode·双指针
历程里程碑38 分钟前
C++ 7vector:动态数组的终极指南
java·c语言·开发语言·数据结构·c++·算法
mit6.82440 分钟前
get+二分|数位dp
算法
sin_hielo44 分钟前
leetcode 2147
数据结构·算法·leetcode
萌>__<新1 小时前
力扣打卡每日一题——缺失的第一个正数
数据结构·算法·leetcode