[英]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);
我也嘗試過使用向量賦值運算符,但是它們有LINEAR復雜度,即O(N)不是常數,所以有沒有辦法在O(1)中交換兩個數組? (通過使用指針或其他東西)
我試過在網上搜索找到了codeforces的鏈接( http://codeforces.com/blog/entry/11971 ),但這沒有幫助。
對向量( std::vector
)使用std::swap
(使用成員函數交換)具有O(1)的復雜性。
來自C ++標准
void swap(vector&x);
10效果:將*的內容和容量()與x的內容和容量交換。
11復雜性: 恆定時間 。
如果使用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中完成了相同的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.