C++ 求和为x的对的索引

C++ 求和为x的对的索引,c++,algorithm,data-structures,C++,Algorithm,Data Structures,给定一个数组,我必须找到和等于x的对的索引 假设数组是arr[5]=123442和sum=5,那么对是1,4,2,3和3,2 我需要存储对的索引,这些索引用于 (1,4) => (0,3) (2,3) => (1,2) (3,2) => (2,4) 所以答案是:0,3,1,2,2,4 我正在使用哈希映射。以下是我的功能: pair<int,int> index[5]; int FindPairs(int arr[],int n, int sum) { in

给定一个数组,我必须找到和等于x的对的索引

假设数组是arr[5]=123442和sum=5,那么对是1,4,2,3和3,2

我需要存储对的索引,这些索引用于

(1,4) => (0,3)
(2,3) => (1,2)
(3,2) => (2,4)
所以答案是:0,3,1,2,2,4

我正在使用哈希映射。以下是我的功能:

pair<int,int> index[5];
int FindPairs(int arr[],int n, int sum) {
    int i, temp,count=0,seta[n],setb[n],j;
bool hash[MAX] = {0}; 
for(i = 0; i < n; ++i)  {
    temp = sum - arr[i];
    if(temp >= 0 && hash[temp]  == 1 ) 
           seta[count++] = i;
    hash[arr[i]] = 1;
}
if(count == 0) return 0;
for(i=0;i<count;++i){
    for(j=0;j<n;j++){
        if( (sum - arr[seta[i]]) ==arr[j]  ) {
            setb[i] = j;
            break;
        }
    }
}
for(i=0;i<count;++i)  index[i] = make_pair(seta[i],setb[i]);
return count;
}
在这里:

n是数组的大小, seta[]由对中第一个数字的索引和 setb[]由该对中第二个数字的索引组成。 我使用Ocount*n计算每对的第二个数字的索引


有没有更有效的方法来实现这一点?

最好为每个值存储一个具有该值的索引列表:

const int MAX_VAL = 5;
std::vector<std::list<int>> mylist(MAX_VAL);
for (i = 0; i < n; ++i)
    mylist[arr[i]].push_back(i);
然后,对于每个值,找到互补值,并打印可以找到该值的所有索引的列表

for(i=0;i<n;++i){
    a = arr[i];
    b = sum - a;
    for (auto j: mylist[b])
        make_pair(i, j); // whatever you want to do with this pair of indices...
}

也许值得检查一下i这与anatolyg的答案是相同的分析,但使用无序的_图进行编码

输出:

0,3 1,2,4


添加基于语法的C++标签;如果我的猜测是错误的,请更正。谢谢您的回复,因此没有比Ocount*n.更有效的解决方案。。那么我该如何解决这个问题呢?如果我从两端开始遍历,或者从左开始遍历,或者从右开始遍历,我必须检查我可以到达两个和为“x”的数字的步数。@Avinasse我不理解你的回答,但你似乎在问一个不同的问题。如果你想解决另一个问题,请另发一篇帖子。谢谢你的回复,我在第一次尝试中使用了无序集,但我担心的是时间问题,因此我回到了数组seta和setb
#include <iostream>
#include <list>
#include <unordered_map>

using namespace std;

void FindPairs(int arr[],int n, int sum, list<pair<int,int>> *pindex) {
  unordered_map<int,list<int>> etoi; // map entry to list of indices
  for( int i=0 ; i<n ; ++i ) etoi[arr[i]].push_back(i);
  for( int i=0 ; i<n ; ++i )
  {
    unordered_map<int,list<int>>::iterator it = etoi.find(sum-arr[i]);
    if( it != etoi.end() ) for( auto j: it->second )
      if( i < j ) pindex->push_back(make_pair(i,j));
  }
}

int main()
{
  int arr[5] = { 1, 2, 3, 4, 2 };
  int sum = 5;

  list<pair<int,int>> index;
  FindPairs( arr, sizeof(arr)/sizeof(int), sum, &index );
  for( auto p: index ) cout << '('<<p.first<<','<<p.second<<") ";
  cout << endl;
}