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);
        
        
    }
};
相关推荐
向阳@向远方1 小时前
第二章 简单程序设计
开发语言·c++·算法
github_czy2 小时前
RRF (Reciprocal Rank Fusion) 排序算法详解
算法·排序算法
许愿与你永世安宁2 小时前
力扣343 整数拆分
数据结构·算法·leetcode
爱coding的橙子2 小时前
每日算法刷题Day42 7.5:leetcode前缀和3道题,用时2h
算法·leetcode·职场和发展
满分观察网友z3 小时前
从一次手滑,我洞悉了用户输入的所有可能性(3330. 找到初始输入字符串 I)
算法
YuTaoShao3 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法二)空间复杂度 O(1)
java·算法·leetcode·矩阵
Heartoxx3 小时前
c语言-指针(数组)练习2
c语言·数据结构·算法
大熊背3 小时前
图像处理专业书籍以及网络资源总结
人工智能·算法·microsoft
满分观察网友z4 小时前
别怕树!一层一层剥开它的心:用BFS/DFS优雅计算层平均值(637. 二叉树的层平均值)
算法
杰克尼5 小时前
1. 两数之和 (leetcode)
数据结构·算法·leetcode