[英]Can someone help me with this problem of finding indices of the pairs of elements of an array that sum to k?
#include <vector>
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, int> nMap;
int a[] = {3,4,5,6,5,7,4};
int k = 10;
for(int i = 0; i < 7; i++) {
int rem = k - a[i];
if(nMap.find(rem) != nMap.end()){
printf("(%d,%d)\n",nMap[rem], i);
}
nMap.insert(std::pair<int,int>(a[i],i));
}
return 0;
}
在上面的程序中,我使用了一個哈希映射來查找元素對的索引,它們的總和等於 k。 上面的代碼運行良好,並為我提供了所需的對
(1,3)
(2,4)
(0,5)
(3,6)
注意:這些是實際加起來為 k 的元素的索引。
但是,這確實適用於輸入int a[] = {1,1,1,1,1,1,1}; int k = 2
int a[] = {1,1,1,1,1,1,1}; int k = 2
給出的 output 是:
(0,1)
(0,2)
(0,3)
(0,4)
(0,5)
(0,6)
但是根據我的說法,我猜 output 必須具有所有對,即 (1,2),(1,3)...(5,6)。 上述問題的正確程序是什么?
輸入1,1,1,1,1,1,1
產生 6+5+4+3+2+1 = 21 = N * (N-1) / 2 = N²/2 - N/2 輸出:
(0, 1) (0, 2) (0, 3) (0, 4) (0, 5) (0, 6) (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) (2, 3) (2, 4) (2, 5) (2, 6) (3, 4) (3, 5) (3, 6) (4, 5) (4, 6) (5, 6)
您需要一個復雜度為 O(N²) 的算法來生成這樣的 output。 您的代碼不起作用,因為復雜度為 O(N) 的代碼無法產生這么多 output。
這是使用無序 map 的更高效的解決方案:
#include <array>
#include <vector>
#include <iostream>
#include <unordered_map>
int main() {
std::array<int, 7> a{3,4,5,6,5,7,4};
std::unordered_map<int, std::vector<std::size_t>> nMap;
for (std::size_t i = 0; i < a.size(); ++i) {
nMap[a[i]].push_back(i);
}
int k = 10;
for (const auto &el : nMap) {
if (nMap.find(k - el.first) == nMap.end()) continue;
for (const auto &left : el.second) {
for (const auto &right : nMap.at(k - el.first)) {
if (left < right) std::cout << '(' << left << ',' << right << ")\n";
}
}
}
return 0;
}
我用一個值的所有索引填充了 map。 現在我可以訪問 O(1) 中的所有索引以獲取目標值。 我迭代 map 中的所有值並打印所有值對。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.