Skip to content

Commit 25cbe90

Browse files
refactor 765
1 parent ae37c8c commit 25cbe90

File tree

1 file changed

+24
-51
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+24
-51
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,33 @@
11
package com.fishercoder.solutions;
22

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-
303
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);
4+
public static class Solution1 {
5+
public int minSwapsCouples(int[] row) {
6+
int swaps = 0;
7+
for (int i = 0; i < row.length - 1; i += 2) {
8+
int coupleValue = row[i] % 2 == 0 ? row[i] + 1 : row[i] - 1;
9+
if (row[i + 1] != coupleValue) {
10+
swaps++;
11+
int coupleIndex = findIndex(row, coupleValue);
12+
swap(row, coupleIndex, i + 1);
13+
}
14+
}
15+
return swaps;
4016
}
41-
}
42-
return swaps;
43-
}
4417

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-
}
18+
private void swap(int[] row, int i, int j) {
19+
int tmp = row[i];
20+
row[i] = row[j];
21+
row[j] = tmp;
22+
}
5023

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;
24+
private int findIndex(int[] row, int value) {
25+
for (int i = 0; i < row.length; i++) {
26+
if (row[i] == value) {
27+
return i;
28+
}
29+
}
30+
return -1;
5531
}
56-
}
57-
return -1;
5832
}
59-
}
6033
}

0 commit comments

Comments
 (0)