|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 765. Couples Holding Hands |
| 5 | + * |
| 6 | + * N couples sit in 2N seats arranged in a row and want to hold hands. |
| 7 | + * We want to know the minimum number of swaps so that every couple is sitting side by side. |
| 8 | + * A swap consists of choosing any two people, then they stand up and switch seats. |
| 9 | + * The people and seats are represented by an integer from 0 to 2N-1, the couples are numbered in order, |
| 10 | + * the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2N-2, 2N-1). |
| 11 | + * The couples' initial seating is given by row[i] being the value of the person who is initially sitting in the i-th seat. |
| 12 | +
|
| 13 | + Example 1: |
| 14 | +
|
| 15 | + Input: row = [0, 2, 1, 3] |
| 16 | + Output: 1 |
| 17 | + Explanation: We only need to swap the second (row[1]) and third (row[2]) person. |
| 18 | +
|
| 19 | + Example 2: |
| 20 | +
|
| 21 | + Input: row = [3, 2, 0, 1] |
| 22 | + Output: 0 |
| 23 | + Explanation: All couples are already seated side by side. |
| 24 | +
|
| 25 | + Note: |
| 26 | + len(row) is even and in the range of [4, 60]. |
| 27 | + row is guaranteed to be a permutation of 0...len(row)-1. |
| 28 | + */ |
| 29 | + |
| 30 | +public class _765 { |
| 31 | + public static class Solution1 { |
| 32 | + public int minSwapsCouples(int[] row) { |
| 33 | + int swaps = 0; |
| 34 | + for (int i = 0; i < row.length - 1; i += 2) { |
| 35 | + int coupleValue = row[i] % 2 == 0 ? row[i] + 1 : row[i] - 1; |
| 36 | + if (row[i + 1] != coupleValue) { |
| 37 | + swaps++; |
| 38 | + int coupleIndex = findIndex(row, coupleValue); |
| 39 | + swap(row, coupleIndex, i + 1); |
| 40 | + } |
| 41 | + } |
| 42 | + return swaps; |
| 43 | + } |
| 44 | + |
| 45 | + private void swap(int[] row, int i, int j) { |
| 46 | + int tmp = row[i]; |
| 47 | + row[i] = row[j]; |
| 48 | + row[j] = tmp; |
| 49 | + } |
| 50 | + |
| 51 | + private int findIndex(int[] row, int value) { |
| 52 | + for (int i = 0; i < row.length; i++) { |
| 53 | + if (row[i] == value) { |
| 54 | + return i; |
| 55 | + } |
| 56 | + } |
| 57 | + return -1; |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments