-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0765-CouplesHoldingHands.cs
39 lines (35 loc) · 1015 Bytes
/
0765-CouplesHoldingHands.cs
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
35
36
37
38
39
//-----------------------------------------------------------------------------
// Runtime: 92ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _0765_CouplesHoldingHands
{
public int MinSwapsCouples(int[] row)
{
int n = row.Length;
int[] pos = new int[n];
for (int i = 0; i < n; i++)
pos[row[i]] = i;
int count = 0;
for (int i = 0; i < row.Length; i += 2)
{
int x = row[i];
if (row[i + 1] == (x ^ 1)) continue;
count++;
Swap(row, pos, i + 1, pos[(x ^ 1)]);
}
return count;
}
private void Swap(int[] row, int[] pos, int x, int y)
{
int temp = row[x];
pos[temp] = y;
pos[row[y]] = x;
row[x] = row[y];
row[y] = temp;
}
}
}