找到总和为x的对的索引

时间:2014-02-08 21:39:51

标签: c++ algorithm data-structures

给定一个数组,我要找到总和等于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)来计算每对的第二个数字的索引。

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

2 个答案:

答案 0 :(得分:0)

为每个值存储具有该值的索引列表可能是个好主意:

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

答案 1 :(得分:0)

这与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)

相关问题