代码技巧,在读取列表时都除2,符合情理并且节省了空间。
class Solution {
private:int get(vector<int>& f,int x){if(f[x]==x){return x;}int newx=get(f,f[x]);return newx;}void add(vector<int>& f,int a,int b){int zua=get(f,a);int zub=get(f,b);if(zua!=zub){f[zua]=zub;}}void init(vector<int>& f){int n=f.size();for(int i=0;i<n;i++){f[i]=i;}}
public:int minSwapsCouples(vector<int>& row) {int length=row.size();int n=length/2;vector<int> Bmap(n);init(Bmap);for(int i=0;i<length;i+=2){int left=row[i]/2;int right=row[i+1]/2;add(Bmap,left,right);}unordered_map<int,int> map;for(int i=0;i<n;i++){int zu=get(Bmap,i);map[zu]++;}int sum=0;for(auto const&[a,b]:map){sum+=b-1;}return sum;}
};