查找总和为 x 的货币对的索引
Find the indices of pairs whose sum is x
给定一个数组,我必须找到总和等于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)
相关文章:
- 数组索引的值没有增加
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 查找最接近的大于当前数字的数字的索引
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 我正在尝试使用 c++ 创建一个货币转换程序,我不知道如何继续
- C++嵌套if语句,基本货币交换
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 并行用于C++17中数组索引范围内的循环
- 跟随整数索引列表的自定义类迭代器
- 如何在for循环中包含两个索引值的测试条件
- D3D11-将混合权重和索引传递到顶点着色器
- 将转换字符键入 int 以用作向量C++的索引
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 如何为圆环创建索引
- 在子集化后将包含索引号的列表列表映射到标准索引序列
- 查找字符在两个索引之间出现的次数
- Azure Kinect 使用正文索引映射裁剪正文
- 查找总和为 x 的货币对的索引