分析:
方法一:贪心,首先将每个数的位置用map保存,遍历偶数索引的数,异或1找到它的情侣,如果不在当前索引i+1的位置上,就用map找到这个数,交换到i+1的位置上,并且更新i+1位置上的数在map中的位置
class Solution { public int minSwapsCouples(int[] row) { int n = row.length; Map<Integer,Integer> map = new HashMap<>(); for(int i = 0; i < n; i++) { map.put(row[i],i); } int res = 0; for(int i = 0; i < n; i += 2) { int j = row[i] ^ 1; // 找到相邻的情侣 奇数就找到小于1的偶数 偶数就找到大于1的奇数 if(row[i+1] == j) continue; int index = map.get(j); row[index] = row[i+1]; map.put(row[i+1],index); row[i+1] = j; res++; } return res; } }
方法二:并查集
class Solution { int[] p; public int minSwapsCouples(int[] row) { int n = row.length; p = new int[n]; for(int i = 0; i < n; i += 2) { p[i] = i; // 初始化 p[i+1] = i; } int res = n / 2; for(int i = 0; i < n; i += 2) { p[find(row[i])] = find(row[i+1]); // 相邻的分到一组 } for(int i = 0; i < n; i++) { if(p[i] == i) res--; } return res; } public int find(int x) { if(x != p[x]) p[x] = find(p[x]); return p[x]; } }