Created
January 14, 2018 11:18
-
-
Save Helenyin123/4e1e321cc5e8e24c8b7073f721373c37 to your computer and use it in GitHub Desktop.
765. Couples Holding Hands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| bhh |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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