[LeetCode] Couples Holding Hands

765. Couples Holding Hands

There are n couples sitting in 2n seats arranged in a row and want to hold hands.

The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).

Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
bool self(vector<int>& A, int cur) {
return A[1] == cur;
}
public:
int minSwapsCouples(vector<int>& A) {
int n = A.size(), res = 0;
unordered_map<int, vector<int>> mp;
for(int i = 0; i < n; i++) {
A[i] = A[i] / 2 * 2;
mp[A[i]].push_back(i);
}

for(int i = 0; i < n; i += 2) {
if(A[i] == A[i + 1]) continue;
bool couple = !self(mp[A[i]], i);
bool other = self(mp[A[i+1]], i + 1);

mp[A[i+1]][other] = mp[A[i]][couple];
swap(A[mp[A[i]][couple]], A[i + 1]);

res++;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/30/PS/LeetCode/couples-holding-hands/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.