C++ 在O(nlogn)时间内查找对和。请不要告诉我O(n)时间的hashmap解

C++ 在O(nlogn)时间内查找对和。请不要告诉我O(n)时间的hashmap解,c++,time-complexity,C++,Time Complexity,请及时给出解决方案。给定一个随机整数数组a和一个数字x。查找并打印数组中与x之和的元素对。数组可能包含重复的元素 样本输入: n=9 数组元素:1 3 6 2 5 4 3 2 4 x=7 样本输出: 16 34 34 2.5 2.5 34 34 以下是我的解决方案,它只适用于独特的元素: #include <bits/stdc++.h> using namespace std; void pairSum(int input[], int size, int x) { sort(i

请及时给出解决方案。给定一个随机整数数组a和一个数字x。查找并打印数组中与x之和的元素对。数组可能包含重复的元素

样本输入:

n=9

数组元素:1 3 6 2 5 4 3 2 4

x=7

样本输出:

16

34

34

2.5

2.5

34

34

以下是我的解决方案,它只适用于独特的元素:

#include <bits/stdc++.h>
using namespace std;
void pairSum(int input[], int size, int x) {
  sort(input, input + size);
  int i = 0, j = size - 1, min = 0, max = 0;
  while (i < j) {
    if ((input[i] + input[j]) > x) {
      j--;
    } else if ((input[i] + input[j]) < x) {
      i++;
    } else {
      if (input[i] > input[j]) {
        min = input[i];
        max = input[j];
        i++, j--;
      } else {
        min = input[i];
        max = input[j];
        i++, j--;
      }
      cout << min << " " << max << endl;
    }
  }

如果我没弄错的话,你也希望打印副本。这只需要对原始算法做一点小小的更改。它标有一条注释:

#include <algorithm>
#include <iostream>
#include <iterator>

template<typename It, typename value_type = typename std::iterator_traits<It>::value_type>
void pairSum(It begin, It end, const value_type& x) {
    if(begin == end) return;

    std::sort(begin, end);
    std::advance(end, -1);
    while(begin < end) {
        if(x < *begin + *end) {
            std::advance(end, -1);
        } else if(*begin + *end < x) {
            std::advance(begin, 1);
        } else {
            std::cout << *begin << " + " << *end << " = " << x << '\n';

            // Only step one iterator. If the next value is the same as the currect,
            // step that iterator.
            if(*begin == *std::next(begin, 1)) std::advance(begin, 1);
            else std::advance(end, -1);
        }
    }
}

int main() {
    std::vector<int> v{9, 1, 3, 6, 2, 5, 4, 3, 2, 4, 7};
    pairSum(v.begin(), v.end(), 10);
}

你还没问一个问题。您应该能够调整您的解决方案以支持重复项。如果您想要唯一对,只需在On中从排序数组中删除重复项。算法不会从虚无中弹出,尤其是经过优化的算法。示例输入:9 1 3 6 2 5 4 3 4 7我不想使用向量。请帮我用数组解决它only@TaslimArifpairSum函数与迭代器一起工作,因此它也与数组一起工作。INTA[]{9,1,3,6,2,5,4,3,2,4,7};pairSumstd::begina,std::enda,10;或pairSuma,a+std::sizea,10;多谢各位。是的,它worked@TaslimArif伟大的不客气!
1 + 9 = 10
3 + 7 = 10
3 + 7 = 10
4 + 6 = 10
4 + 6 = 10