uicccui 2021-11-07 00:50 采纳率: 42.9%
浏览 34
已结题

Query数据结构与算法问题

题目描述

We have a set of strings (set A) and a set of queries (set B). Each query is to check whether a string exists in set A or not. If yes, output this string.
Your task is to implement the following function:

void query(string A[], int n, string B[], int m);

Here, n is the number of strings in set A, m is the number of strings in set B. 1<=n,m<=500,000.
Submit the function only.
输入描述

No input.
输出描述

Output the strings in set B which exist in set A. The output should follow the original order of the strings in set B.
提示

For example,
A[0]=“ABC”, A[1]=“CD”, A[2]=“D”
B[0] = “A”, B[1] =“CD”, B[2]=“BC”, B[3]=“ABC”,
then you should output:
CD
ABC

希望给出代码

  • 写回答

2条回答 默认 最新

  • 广大菜鸟 2021-11-07 02:34
    关注
    //利用键值对,查询比较快,时间复杂度可以达到O(n)
    #include<iostream>
    #include<string>
    #include<map>
    using namespace std;
    void query(string A[], int n, string B[], int m) {
        map<string, int>num_map;
        for (int i = 0; i < n;i++) {
            pair<string, int>value(A[i], 1);
            num_map.insert(value);
        }
        for (int i = 0; i < m; i++) {
            map<string, int>::iterator it = num_map.find(B[i]);
            if (it != num_map.end()) {
                cout << B[i] << endl;
            }
        }
    }
    int main() {
        string A[] = { "ABC", "CD","D" };
        string B[] = { "A","CD","BC","ABC" };
        query(A, 3, B, 4);
    }
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 11月18日
  • 已采纳回答 11月10日
  • 创建了问题 11月7日

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵