Couples Holding Hands LeetCode solution in C++

1
class Solution {
2
public:
3
int minSwapsCouples(vector<int> &row) {
4
int cnt = 0, n = row.size();
5
// first of all making row element equal ex for [0,1],[2,3] --> [0,0]
6
// ,[2,2]
7
for (auto &x : row) {
8
if (x & 1) {
9
x--;
10
}
11
}
12

13
for (int i = 0; i < n; i += 2) {
14
int ele = row[i];
15
int j = i + 1;
16
// for every num find location of equal one,
17
while (j < n and row[j] != ele) j++;
18
if (j != i + 1) {
19
// not in same couch then cnt++ , and swap
20
swap(row[j], row[i + 1]);
21
cnt++;
22
}
23
}
24
return cnt;
25
}
26
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0