Skip to content

Instantly share code, notes, and snippets.

@Helenyin123
Created January 14, 2018 11:18
Show Gist options
  • Select an option

  • Save Helenyin123/4e1e321cc5e8e24c8b7073f721373c37 to your computer and use it in GitHub Desktop.

Select an option

Save Helenyin123/4e1e321cc5e8e24c8b7073f721373c37 to your computer and use it in GitHub Desktop.
765. Couples Holding Hands
public int minSwapsCouples(int[] row) {
Map<Integer, Integer> map = new HashMap<>();
Set<Integer> visited = new HashSet<>();
// record the index of row
for (int i = 0; i < row.length; i++) {
map.put(row[i], i);
}
int count = 0;
for (int i = 0; i < row.length; i += 2) {
if (!visited.contains(i)) {
int loop = 0; int cur = i;
while (!visited.contains(cur)) {
visited.add(cur);
int first = map.get(row[cur] ^ 1);
visited.add(first);
cur = first ^ 1;
loop ++;
}
count += loop - 1;
}
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment