转载源:点击打开链接
class Solution {
public:
int minSwapsCouples(vector<int>& row) {
vector<int> pos(row.size(), 0); //记录第i个人在row数组中的位置
for(int i=0; i<row.size(); i++)
pos[row[i]] = i;
int res = 0;
for(int i=0; i<row.size(); i+=2) {
if(row[i]/2 == row[i+1]/2) continue; //是夫妇的话不需要调整
int huswhere = 0; //假设i是妻子,huswhere是丈夫在row数组中的位置
if(row[i]%2 == 0) huswhere = pos[row[i]/2*2+1];
else huswhere = pos[row[i]/2*2];
res++;
pos[row[i+1]] = huswhere; //更新pos数组
swap(row[i+1], row[huswhere]);
}
return res;
}
};