class Solution {
public:
int check(int a, int b) {
return (abs(a - b) == 1) && ((min(a, b) + 2) % 2 != 1);
}
int minSwapsCouples(vector<int>& row) {
int n = row.size(), ans = 0, pos = 0;
while (pos < n) {
while (pos < n && check(row[pos], row[pos + 1])) pos += 2;
if (pos == n) break;
int a = (row[pos] + 2) % 2 == 0 ? row[pos] + 1 : row[pos] - 1;
for (int i = pos + 1; i < n; i++) {
if (row[i] != a) continue;
row[i] = row[pos + 1];
break;
}
pos += 2;
ans += 1;
}
return ans;
}
};
765. 情侣牵手
于 2023-11-11 21:37:43 首次发布