排序查询如何访问私有向量值
Sorting ques how to access the private vector values
我在排序方面正在做这个问题,我认为可以通过堆排序或快速排序对此进行排序。
有一个大小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(,查看另一个答案,更复杂,但复杂性
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- C++从另一个类访问公共静态向量的正确方法是什么
- 访问存储在向量C++中的结构的多态成员
- 如何从静态向量访问类元素?
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- 从父类的向量访问子类函数,而无需向下转换
- 如何使用常数向量访问成员函数
- 如何从C 向量访问单个单词
- 从C++中传递给函数的指针向量访问矩阵
- 多向量访问与本地对象
- C 迭代器与用于向量访问的指针
- 从向量访问成员功能
- 如何在 c++ 中从 "pointer-to-objects" 向量访问对象
- 如何从双精度向量的向量访问数据
- 从指针向量访问成员函数?C++
- 如何使用SWIG Python从内部向量访问c ++对象方法
- 无法从向量访问对象的getter
- 从向量访问某些类函数C++的问题
- 从基类类型的向量访问派生类方法
- 从对象指针向量访问对象