[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
今天看启发式合并的时候发现一个题解里面直接对 set 进行 swap,就好奇其时间复杂度。测了一下,容器的 swap 应该是 O(1) 左右的。
vector 的 swap 时间近似 O(1)
set, map 的 swap 时间常数稍大,是 vector 的 2 倍左右
string 比 vector 要快得多
priority_queue 也可以 swap
set 的测试代码:
#include<bits/stdc++.h> using namespace std; #define rep(i, l, r) for(int i =
l; i <= (r); ++ i) const int N = 1e5 + 10, M = 1e7 + 10; inline bool check(int x
){ return __lg(x) % 3; } int is[M]; set<int> v1, v2, v3; void init() // 预处理随机数据
{ clock_t startTime,endTime; startTime = clock();//计时开始 srand(time(0)); rep(i, 1
, N) v1.insert(rand()); rep(i, 1, N) v2.insert(rand()); rep(i, 1, N) v3.insert(
rand()); rep(i, 1, M - 1) is[i] = check(rand()); // 这样是让数据更随机,防止编译器优化掉 endTime =
clock();//计时结束 cout << "The run time is: " <<(double)(endTime - startTime) /
CLOCKS_PER_SEC<< "s" << endl; } void swap_test() { clock_t startTime,endTime;
startTime= clock();//计时开始 int t; rep(i, 1, M - 1) // 对长度为 10^5 的容器随机交换 10^7 次 {
t= is[i]; if(t == 0) swap(v1, v2); if(t == 1) swap(v1, v3); if(t == 2) swap(v3,
v2); } endTime = clock();//计时结束 cout << "The run time is: " <<(double)(endTime -
startTime) / CLOCKS_PER_SEC << "s" << endl; } int main() { init(); swap_test();
return 0; }