我们如何在恒定复杂度或O(1)中交换2个数组
How can we swap 2 arrays in constant complexity or O(1)?
如何在恒定复杂度或O(1)
中交换2个数组?我们有办法做到这一点吗?我试过使用指针,但它给出了一个错误
此外,这也无济于事,因为它只是交换指针,而不是数组:
#include <algorithm>
int AA[100], *A=AA, BB[100], *B=BB;
swap(A, B);
我也尝试过使用向量赋值运算符,但它们具有线性复杂性,即O(N)
不是常数。那么,有什么方法可以在O(1)
中交换两个阵列吗?(通过使用指针或其他东西)
我试着在互联网上搜索,发现了一个代码部队的链接(http://codeforces.com/blog/entry/11971),但这于事无补。
对向量(std::vector
)使用std::swap
(使用成员函数交换)具有O(1)
的复杂性。
来自C++标准:
void swap(vector& x);
10效果:将*this的内容和容量()与x.的内容和能力交换
11复杂性:恒定时间。
你可以"交换阵列";如果它们是用运算符CCD_ 7动态分配的,则具有恒定的时间。在这种情况下,您实际上只能交换指向数组的第一个元素的指针。
例如:
#include <iostream>
#include <algorithm>
int main() {
int **a = new int *[2];
a[0] = new int[5] { 0, 1, 2, 3, 4 };
a[1] = new int[5] { 5, 6, 7, 8, 9 };
for ( size_t i = 0; i < 2; i++ ) {
for ( size_t j = 0; j < 5; j++ ) {
std::cout << a[i][j] << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
std::swap( a[0], a[1] );
for ( size_t i = 0; i < 2; i++ ) {
for ( size_t j = 0; j < 5; j++ ) {
std::cout << a[i][j] << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
delete [] a[0];
delete [] a[1];
delete [] a;
return 0;
}
输出为:
0 1 2 3 4
5 6 7 8 9
5 6 7 8 9
0 1 2 3 4
事实上,在std::vector
中也进行了相同的操作。
相关文章:
- 通过交换元素使数组相同
- 如何在数组中交换最小和最大的位置?
- 交换函数不是在 C++ 中交换 2D 数组的元素
- 如何交换数组中的元素?
- C++:交换矩阵的行:使用单维数组
- 使用指针交换数组的内容
- 交换数组
- 代码是否交换数组的两个数字
- C++ 通过移动而不是复制来交换数组元素
- 为什么它不交换数组中的两个整数?
- 当数组是类的数据成员时,如何使用指针交换数组
- 无法在C++中交换数组中的对象
- 交换数组中的 2 个项目,但不通过引用传递它
- 我不知道如何打印数组,反过来,我也无法弄清楚如何交换数组中的元素
- 交换数组中的位置
- 不能交换数组元素 C++
- 如何在c++中基于输入整数值交换数组
- 在c++中可视化交换数组值
- 递归地交换数组中的元素
- 交换数组C++中的值