排序查询如何访问私有向量值

Sorting ques how to access the private vector values

本文关键字:向量 访问 查询 何访问 排序      更新时间:2023-10-16

我在排序方面正在做这个问题,我认为可以通过堆排序或快速排序对此进行排序。

有一个大小n的整数数组a无法直接访问。但是,您可以对表单A [i]&lt的查询的查询得到真实或错误的响应;A [J]。鉴于A只有一个重复对,并且所有元素都与众不同。因此,它具有N-1不同的元素和1个元素,与N-1元素之一相同。您的任务是确定A。

中两个相同元素的索引。
class hiddenVector {
        private:
             vector <int> data; // you cannot directly access this in your code since this is a private element
        public:
             int getSize();// it returns a non-negative integer equal to the size of the class member data.
             bool iLessThanj(int i, int j); // returns true if and only if data[i] is strictly less than data[j]
};

您可以创建一个新的向量,其中包含隐藏向量的索引,然后使用隐藏向量的公共方法iLessThanj()对其进行排序。最后,浏览排序的索引以找到一对相等的元素,它们在排序后与 iLessThanj(i, i+1) == false相邻,仅对它们又相邻。

这在时间上具有O(nlogn(的复杂性,并且在内存中具有O(n(。

hiddenVector a; // {1, 3, -2, -4, 3, 7} for example
// construct indexes array
std::vector<int> a_ind (a.getSize ());
for (int i = 0; i < a.getSize(); i++)
  a_ind[i] = i;
// now a_ind = {0, 1, 2, 3, 4, 5}
// sort it
std::sort(begin(a_ind), end(a_ind),
      [&a] (int i, int j) { return a.iLessThanj(i, j); }
);
// now a_ind = {3, 2, 0, 1, 4, 5} 
// and it is equal to sequence of indexes in sorted hidden vector
// finally, compute an answer to your problem
std::pair<int, int> res = {};
for (int k = 0; k < a_ind.size()-1; k++) {
  int i = a_ind[k];
  int j = a_ind[k+1];
  if (!a.iLessThanj(i, j)) {
    res.first = i;
    res.second = j;
    break;
  }
}
// now res = {1, 4}

ps在评论中进行讨论的速度测试结果(以-O3运行(:

N      squared_algo sublinear_algo
10     2.259e-07    1.1653e-06 
100    4.8259e-06   8.5859e-06 
1000   0.000218602  0.000118063 
10000  0.0138744    0.000718756 
100000 0.913739     0.00876182

全速测试编码为

鉴于A只有一个重复对,其余所有元素都是不同的。因此,它具有N-1不同的元素和1个元素,与N-1元素之一相同。您的任务是确定A。

中两个相同元素的索引

您无需访问元素,索引 a b 是当iLessThanj(a, b)返回false时的解决方案,并且iLessThanj(b, a)也返回false(当然使用,b != a (

所以类似:

hiddenVector v;
... initialization of v
int n = v.getSize();
for (int a = 0; a < n; ++a) {
  int b;
  for (b = a+1; b < n; ++b) {
     if (!v.iLessThanj(a, b) && !v.iLessThanj(b, a)) {
       std::cout << "element is the same at indexes " << a << " and " << b << std::endl;
       break;
     }
  }
  if (b < n)
    break;
}

P.S。复杂性是o(n^2(,查看另一个答案,更复杂,但复杂性