版本比较
一篇水题解~
正文
增加 13 行删除 13 行
54 行未改动55565758595960616162636364656667676869697071717273737475757677777879808182838485868687888989909192939495959697989912 行未改动11211311411511611611711811912015 行未改动54 行未改动int solve(vector<int> pos, vector<int> val){ // 随机打乱位置和值集合的顺序,避免最坏情况 shuffle(pos.begin(), pos.end(), rd); shuffle(val.begin(), val.end(), rd);
// 基本情况:如果候选值集合只剩一个元素,那它必然是重复元素 if(val.size() == 1) if(val.size() == 1) return val[0];
// 将位置集合按60%比例分成左右两部分 vector<int> L, R; int lim = max(1, (int)(pos.size() * 0.6));
// 分配位置到左子集(前60%) for(int i = 0; i < lim; i++) for(int i = 0; i < lim; i++) L.push_back(pos[i]);
// 剩余位置分配到右子集 for(int i = lim; i < pos.size(); i++) for(int i = lim; i < pos.size(); i++) R.push_back(pos[i]);
vector<int> vL, vR; // 记录在左右子集中出现的候选值
// 检查每个候选值在左子集中的出现情况 for(int x : val){ if(chiedi(L, x) == true){ vL.push_back(x); // 在左子集中出现 } else { vR.push_back(x); // 不在左子集中出现(在右子集) } }
// 关键判断:如果左子集中出现的值数量比左子集位置数少1 // 说明重复元素在左子集中 if(vL.size() == (int)L.size() - 1) if(vL.size() == (int)L.size() - 1) return solve(L, vL); else { // 检查左子集中的每个值是否也在右子集中出现 // 如果某个值在两个子集中都出现,它就是重复元素 for(int x : vL){ if(chiedi(R, x) == true) if(chiedi(R, x) == true) return x; } // 否则重复元素在右子集中 return solve(R, vR);12 行未改动 pos.push_back(i); // 位置0到N-1 val.push_back(i); // 可能的值0到N-1 } pos.push_back(N); // 添加第N个位置(总共N+1个位置)
return solve(pos, val);}
```15 行未改动