https://leetcode.com/problems/couples-holding-hands/description/
N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.
The people and seats are represented by an integer from 0 to 2N-1, the couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2N-2, 2N-1).
The couples' initial seating is given by row[i] being the value of the person who is initially sitting in the i-th seat.
Example 1:
Input: row = [0, 2, 1, 3]
Output: 1
Explanation: We only need to swap the second (row[1]) and third (row[2]) person.
Example 2:
Input: row = [3, 2, 0, 1]
Output: 0
Explanation: All couples are already seated side by side.
Note:
len(row) is even and in the range of [4, 60].
row is guaranteed to be a permutation of 0...len(row)-1.
思路:
- 要求最小交换次数,感觉是个贪心,尝试证明。
- 每次交换存在两种情况:
a. 两组间交换后同时满足配对。
b.两组间交换后只有一组满足配对。 - 显然每次优先处理 a 情况的配对组。
- 对于 b 情况,发现如果将每相邻的两个人组成一个节点,存在交换需求的两点间连上一条线,此时所有的节点一定形成了一条链。每次交换能使得两点间连线消去。很明显此时不管先消去哪条线,最后都需要 n-1次交换。
- 结合 a 情况,此时属于 a 情况的点是自动形成环,不会影响后续交换,贪心交换成立。
- 综上:贪心策略为每碰到一个不配对的相邻两人,贪心地从后面找一个能满足此配对的交换,记录总次数即可
class Solution {
public:
bool isCouple(int a, int b) {
return a/2 == b/2;
}
int ans = 0;
int minSwapsCouples(vector<int>& row) {
int n = row.size();
for (int i = 0; i < n; i = i + 2) {
if (!isCouple(row[i], row[i + 1])) {
int u = i + 1;
for (int v = u + 1; v < n; v++) {
if (isCouple(row[i], row[v])) {
int t = row[u];
row[u] = row[v];
row[v] = t;
ans++;
}
}
}
}
return ans;
}
};
网友评论