forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_765.java
33 lines (30 loc) · 963 Bytes
/
_765.java
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
package com.fishercoder.solutions;
public class _765 {
public static class Solution1 {
public int minSwapsCouples(int[] row) {
int swaps = 0;
for (int i = 0; i < row.length - 1; i += 2) {
int coupleValue = row[i] % 2 == 0 ? row[i] + 1 : row[i] - 1;
if (row[i + 1] != coupleValue) {
swaps++;
int coupleIndex = findIndex(row, coupleValue);
swap(row, coupleIndex, i + 1);
}
}
return swaps;
}
private void swap(int[] row, int i, int j) {
int tmp = row[i];
row[i] = row[j];
row[j] = tmp;
}
private int findIndex(int[] row, int value) {
for (int i = 0; i < row.length; i++) {
if (row[i] == value) {
return i;
}
}
return -1;
}
}
}