Leetcode765 question-couple holding hands

topic

N couples sit on 2N seats in a row and want to hold each other's hands. Calculate the minimum number of exchanges of seats so that each couple can sit side by side. Any two people can be selected for one exchange, and they can stand up and exchange seats.

People and seats are represented by integers from 0 to 2N-1. The lovers are numbered in sequence, the first pair is (0, 1), the second pair is (2, 3), and so on, the last pair is (2N- 2, 2N-1).

The initial seat row[i] of these couples is determined by the person who initially sat in the i-th seat.

Example 1:

Input: row = [0, 2, 1, 3]
Output: 1
Explanation: We only need to swap the positions of row[1] and row[2].
Example 2:

Input: row = [3, 2, 0, 1]
Output: 0
Explanation: No need to exchange seats, all couples can already hold hands.
Description:

len(row) is an even number and the value is in the range [4, 60].
It can be guaranteed that row is a complete permutation of the sequence 0...len(row)-1.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/couples-holding-hands
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Code (Java)

public class Solution {
    
    
    public int minSwapsCouples(int[] row) {
    
    
        int n = row.length;
        int total = n / 2;
        int[] f = new int[total];
        for (int i = 0; i < total; i++) {
    
    
            f[i] = i;
        }

        for (int i = 0; i < n; i += 2) {
    
    
            int l = row[i] / 2;
            int r = row[i + 1] / 2;
            add(f, l, r);
        }

        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < total; i++) {
    
    
            int fx = getf(f, i);
            map.put(fx, map.getOrDefault(fx, 0) + 1);
        }
        
        int ret = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    
    
            ret += entry.getValue() - 1;
        }
        return ret;
    }

    public int getf(int[] f, int x) {
    
    
        if (f[x] == x) {
    
    
            return x;
        }
        int newf = getf(f, f[x]);
        f[x] = newf;
        return newf;
    }

    public void add(int[] f, int x, int y) {
    
    
        int fx = getf(f, x);
        int fy = getf(f, y);
        f[fx] = fy;
    }
}

Guess you like

Origin blog.csdn.net/m0_50654102/article/details/113808077