跳转至

情侣牵手⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
private:
    int p[31];
    void unionSets(int a, int b) {
        p[find(a)] = find(b);
    }
    int find(int x) {
        if (p[x] != x) p[x] = find(p[x]);
        return p[x];
    }
public:
    int minSwapsCouples(vector<int>& row) {
        int n = row.size(), m = n / 2;
        for (int i = 0; i < m; i++) p[i] = i;

        for (int i = 0; i < n; i += 2) 
            unionSets(row[i] / 2, row[i + 1] / 2);

        int cnt = 0;
        for (int i = 0; i < m; i++) {
            if (i == find(i)) cnt++;
        }
        return m - cnt;
    }
};