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);
        
        
    }
};
相关推荐
shehuiyuelaiyuehao4 分钟前
算法44,模拟算法,数青蛙
算法·哈希算法·散列表
hanlin0318 分钟前
刷题笔记:力扣第287题-寻找重复数
笔记·算法·leetcode
kevin_kang28 分钟前
第02章 对话时间线与延迟分析
算法
科学实验家38 分钟前
最小生成树:Prim,kruskal
数据结构·c++·算法
学习智者41 分钟前
《玄》IDE v3.6.3重磅发布:全功能修复与性能飞跃
开发语言·c++·ide·算法·中文语言 玄
Jasmine_llq44 分钟前
《P10263 [GESP202403 八级] 公倍数问题》
算法·数论·快速 io 优化·埃氏筛(倍数枚举)·线性遍历求和
橘子汽水1681 小时前
Leetcode 322 279 零钱兑换,完全平方数
算法·leetcode
kevin_kang1 小时前
第01章 VoiceAgent 的总体架构与完整流程
算法
Lintongzg1 小时前
KV-Cache 的显存账本:长上下文、并发与量化剪枝的取舍
算法·机器学习·剪枝
小孩玩什么1 小时前
深入理解字符串匹配算法:BF算法,KMP算法
java·c语言·开发语言·数据结构·c++·算法