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);
        
        
    }
};
相关推荐
黎雁·泠崖5 分钟前
二叉树基础精讲(上):树形结构 · 二叉树概念 · 性质 · 遍历 · 基础操作全解析
java·数据结构·算法
Q741_1477 分钟前
每日一题 力扣 2515.到目标字符串的最短距离 循环数组 C++题解
c++·算法·leetcode
Dfreedom.10 分钟前
聚类算法对比分析:K-Means、DBSCAN 与层次聚类
人工智能·算法·机器学习·kmeans·聚类
cmpxr_11 分钟前
【C】结构体的内存对齐
c语言·开发语言·算法
ICscholar18 分钟前
MoE负载均衡损失 & 梯度累加除法
人工智能·学习·算法
清辞85321 分钟前
【Day4】C++竞赛每日练习
数据结构·c++·算法
代码飞天23 分钟前
算法与数据结构之栈、队列
数据结构·算法
写代码写到手抽筋35 分钟前
线性插值与Sinc插值的数学原理及实战
算法
孤飞8 小时前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
技术专家9 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节