我们如何以恒定复杂度或O(1)交换2个数组? 我们有办法做到这一点吗? 我试过使用指针,但它给出了错误
加上这个不会有帮助,因为它只是交换指针而不是数组
#include <algorithm>
int AA[100], *A=AA, BB[100], *B=BB;
swap(A, B);
我也尝试过使用向量赋值运算符,但它们有LINEAR复杂度,即O(N)不是常数,所以我们有什么方法可以在O(1)中交换两个数组? (通过使用指针或其他东西)
我试过在网上搜索找到了代码链接(http://codeforces.com/blog/entry/11971),但这没有帮助。
答案 0 :(得分:3)
对向量(std::swap
)使用std::vector
(使用成员函数交换)的复杂度为O(1)。
来自C ++标准
void swap(vector&amp; x);
10效果:将*的内容和容量()与x的内容和容量交换。
11复杂性:恒定时间。
你可以&#34;交换阵列&#34;如果它们是使用operator new动态分配的,则具有恒定时间。在这种情况下,您确实只能交换指向数组的第一个元素的指针。
例如
#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中完成了相同的操作。