[2018-09-30] [LeetCode-Week4] 765. Couples Holding Hands 贪心

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.


思路:

  1. 要求最小交换次数,感觉是个贪心,尝试证明。
  2. 每次交换存在两种情况:
    a. 两组间交换后同时满足配对。
    b.两组间交换后只有一组满足配对。
  3. 显然每次优先处理 a 情况的配对组。
  4. 对于 b 情况,发现如果将每相邻的两个人组成一个节点,存在交换需求的两点间连上一条线,此时所有的节点一定形成了一条链。每次交换能使得两点间连线消去。很明显此时不管先消去哪条线,最后都需要 n-1次交换。
  5. 结合 a 情况,此时属于 a 情况的点是自动形成环,不会影响后续交换,贪心交换成立。
  6. 综上:贪心策略为每碰到一个不配对的相邻两人,贪心地从后面找一个能满足此配对的交换,记录总次数即可

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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,871评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,189评论 0 23
  • 眉飞胭脂红 1) 图书馆每天进出的学生多达几百人,我不常记得他们的模样。也许在他们的眼里,我亦是个不多言,比较高冷...
    眉飞胭脂红阅读 312评论 0 2
  • 虹桥的河 当我们在白龙山俯瞰虹桥平原,平畴沃野犹如一张巨大的绿叶,河网似密密麻麻的脉纹纵横交织着,流经镇内的几条河...
    倪金诗章阅读 639评论 0 0

友情链接更多精彩内容