为什么我使用地图的代码不适用于多个测试用例,但适用于第一个测试用例?

问题描述 投票:0回答:1

我的代码试图使用地图找出总和为目标的元素对。但是,它仅适用于第一个测试用例。
即使它接受多个测试用例作为输入。它仅给出第一个测试用例的输出。请帮我找出问题并解决它。

Sample Input 1 :
2
4 9
2 7 11 13
5 1
1 -1 -1 2 2
Sample Output 1:
2 7
-1 2
-1 2

示例1的说明:
对于第一个测试用例,我们可以看到 2 和 7 之和等于 9,并且它是唯一有效的对。

对于第二个测试用例,有两个有效对 (-1,2) 和 (-1,2),加起来为 1。

Sample Input 2 :
1
4 16
2 7 11 13
Sample Output 2 :
-1 -1

我编写了以下代码,但它只是给出第一个测试用例的结果。例如,如果输入是

3
4 9
2 7 11 13
5 1
1 -1 -1 2 2
1 4
2

它是给予

2 7 
-1 2

当它应该是

2 7
-1 2
1 2
-1 -1
#include<bits/stdc++.h>
#include <iostream>
#include <vector>

using namespace std;

vector<pair<int,int>> twoSum(vector<int>& arr, int target, int n)
{
    // Write your code here. 
    vector<pair<int,int>> vect;
    map<int,int>mp;
    for(int i=0;i<n;i++){
        int a=target-arr[i];
        
        if((mp.empty())||(mp.count(a)==0)){
             mp[arr[i]]=1;
        }
        else{
            vect.push_back( make_pair(arr[i],a) );
            mp.erase(a);
        }
    }
    return vect;
}
#include <iostream>
#include <vector>

using namespace std;


int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin>>t;
    while(t--)
    {
        int n,target;
        cin>>n>>target;
        vector<int> v(n);
        for(int i=0;i<n;i++)
        {
            cin>>v[i];
        }
        
        vector<pair<int,int>> ans=twoSum(v,target,n);
        for(auto i:ans)
        {
            if(i.first<i.second)
                cout<<i.first<<" "<<i.second<<"\n";
            else
                cout<<i.second<<" "<<i.first<<"\n";
        }
        
    }
}
c++ vector stl
1个回答
0
投票

问题在于,如果您有多个具有相同值的数字,您将无法处理。检查

mp.count(a) == 0
,而不是
mp[a] == 0
。这不会检查
a
是否存在,但如果不存在则插入
a
,并且还会检查其映射计数是否为
0

然后在

true
分支中,减去 1
a
而不是使用
erase(a)

示例:

std::vector<std::pair<int, int>> twoSum(std::vector<int>& arr, int target) {
    std::vector<std::pair<int, int>> vect;
    std::map<int, int> mp;
    for (std::size_t i = 0; i < arr.size(); i++) {
        int a = target - arr[i];

        if (mp[a] == 0) {
            ++mp[arr[i]];
        } else {
            vect.emplace_back(arr[i], a);
            --mp[a]; // don't erase, subtract
        }
    }
    return vect;
}

演示

© www.soinside.com 2019 - 2024. All rights reserved.