查找总和为 x 的货币对的索引

Find the indices of pairs whose sum is x

本文关键字:货币 索引 查找      更新时间:2023-10-16

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

假设数组为 arr[5] = 1 2 3 4 2 且 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[]由货币对中第二个数字的索引组成。

我正在使用O(count*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 <= j以避免两次打印同一对。

请注意,一般情况的复杂性必须O(count*n):最坏的情况是由相同数字组成的数组:

数组: 1, 1, 1

, 1, 1

总额: 2

答案: (0, 0), (0, 1), (

0, 2), ..., (4, 4)

打印的复杂性:O(n^2)O(count*n),因为这里的count等于n

这与anatolyg的答案相同,但使用unordered_map编码。

#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;
}

输出:

(0,3) (1,2) (2,4)