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);
        
        
    }
};
相关推荐
Black蜡笔小新4 分钟前
自动化AI算法训练服务器DLTM零代码私有化部署筑牢企业AI落地根基
人工智能·算法·自动化
wWYy.4 分钟前
算法:最大子数组和
算法
吃着火锅x唱着歌8 分钟前
LeetCode 3829.设计共享出行系统
算法·leetcode·职场和发展
炸薯条!10 分钟前
二叉树的链式表示
数据结构·算法
CHHH_HHH11 分钟前
【C++】二叉搜索树全面升级,深度剖析AVL树
开发语言·数据结构·c++·算法·stl
Mumu121812 分钟前
P3211 [HNOI2011] XOR和路径
算法
高一学习c++会秃头吗13 分钟前
页面置换算法实现
算法
yuanyuan2o220 分钟前
Transformers NLP 任务:阅读理解问答
人工智能·算法·自然语言处理·nlp·github
菜菜的顾清寒31 分钟前
力扣HOT100(52)动态规划 - 最长递增子序列
算法·leetcode·动态规划
WBluuue37 分钟前
数据结构与算法:树上启发式合并
数据结构·c++·算法·启发式算法