LeetCode765.情侶牽手(Java)
阿新 • 來源:網路 • 發佈:2021-02-15
技術標籤:LeetCode刷題
題目
N 對情侶坐在連續排列的 2N 個座位上,想要牽到對方的手。
計算最少交換座位的次數,以便每對情侶可以並肩坐在一起。一次交換可選擇任意兩人,讓他們站起來交換座位。
人和座位用 0 到 2N-1 的整數表示,情侶們按順序編號,第一對是 (0, 1),第二對是 (2, 3),以此類推,最後一對是(2N-2, 2N-1)。
這些情侶的初始座位 row[i] 是由最初始坐在第 i 個座位上的人決定的。
示例 1:
輸入: row = [0, 2, 1, 3]
輸出: 1
解釋: 我們只需要交換row[1]和row[2]的位置即可。
示例 2:
輸入: row = [3, 2, 0, 1]
輸出: 0
解釋: 無需交換座位,所有的情侶都已經可以手牽手了。
分析
找規律,(2N-2,2N-1),成對的一個是偶數一個奇數。
如果前面是偶數,後面那個就是前面數+1;
如果前面是奇數,後面那個是前面數 -1;
程式碼
public int minSwapsCouples(int[] row) {
int count = 0;
int left = 0;
while (left < row.length) {
int right = judge(row[left]);
int index = left + 1;
if (row[index] != right) {
while (index < row.length && row[index] != right) {
index++;
}
count++;
swap(row, left, index);
}
left += 2;
}
return count;
}
public int judge(int num) {
if (num % 2 == 0) {
return num + 1;
} else {
return num - 1;
}
}
public void swap(int[] row, int left, int right) {
int temp = row[left + 1];
row[left + 1] = row[right];
row[right] = temp;
}
參考

class Solution {
public int minSwapsCouples(int[] row) {
int res = 0;
for(int i = 0;i<row.length;i+=2){
int key = row[i];
if(row[i + 1] == (key ^ 1)){
continue;
}
res++;
for(int j = i + 1;j<row.length;j++){
if(row[j] == (key ^ 1)){
row[j] = row[i + 1];
row[i + 1] = key ^ 1;
}
}
}
return res;
}
}
end.
