//问题解决了,谢谢楼上各位大神们。如果按我的想法,正确的代码如下: #include<iostream> #include<vector> #include<unordered_map> using namespace std; pair<int, int> gettwonums(vector<int>& A,const int& K) {  unordered_map<int,int> res;  for (auto &a : A)  {   auto ret=res.insert({ a,1 });   if (ret.second == false)    (ret.first)->second++;  }  for (auto &a :A)  {   auto ret = res.insert({ K - a,1 });   if (ret.second == false)   {    if ((2 * a == K&&res[a]> 1)|| (2 * a != K))     return make_pair(a, K - a);   }  }  return  make_pair(0,0); } int main() {  vector<int> A = { 5,8,6,7,9,2};  auto a = gettwonums(A, 10);  cout << a.first << " " << a.second;  system("pause"); } //根据楼上大神的提示,其实有更简单的方法,代码如下: pair<int, int> gettwonums2(vector<int>& A, const int& K) {  int len = A.size();  unordered_set<int> res;  res.insert(A[0]);  for (int i = 1;i < len;i++)  {   if(res.find(K-A[i])!=res.end())    return make_pair ( A[i], K - A[i]);   res.insert(A[i]);  }  return{ 0,0 }; }
点赞 评论
牛客网
牛客网在线编程
牛客网题解
牛客企业服务