forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
couples-holding-hands.cpp
34 lines (32 loc) · 1.08 KB
/
couples-holding-hands.cpp
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
28
29
30
31
32
33
34
// Time: O(n)
// Space: O(n)
class Solution {
public:
int minSwapsCouples(vector<int>& row) {
int N = row.size() / 2;
vector<vector<int>> couples(N);
for (int seat = 0; seat < row.size(); ++seat) {
couples[row[seat] / 2].emplace_back(seat / 2);
}
vector<vector<int>> adj(N);
for (const auto& couple : couples) {
adj[couple[0]].emplace_back(couple[1]);
adj[couple[1]].emplace_back(couple[0]);
}
int result = 0;
for (int couch = 0; couch < N; ++couch) {
if (adj[couch].empty()) {
continue;
}
int couch1 = couch;
int couch2 = adj[couch1].back(); adj[couch1].pop_back();
while (couch2 != couch) {
++result;
adj[couch2].erase(find(adj[couch2].begin(), adj[couch2].end(), couch1));
couch1 = couch2;
couch2 = adj[couch1].back(); adj[couch1].pop_back();
}
}
return result; // also equals to N - (# of cycles)
}
};