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);
        
        
    }
};
相关推荐
万事可爱^26 分钟前
HDBSCAN:密度自适应的层次聚类算法解析与实践
算法·机器学习·数据挖掘·聚类·hdbscan
大数据追光猿2 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!3 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉3 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生3 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴3 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing3 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财3 小时前
加油站(力扣134)
算法·leetcode·职场和发展
王老师青少年编程3 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
qy发大财3 小时前
柠檬水找零(力扣860)
算法·leetcode·职场和发展