算法设计与分析第五次作业

#leetcode765. Couple Holding Hands
题目描述如下:

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.

这道题要求对一个数组内的值进行交换,使得每个数的旁边都有其“配对数”,由于是要两两配对的原因,而且总个数为偶数个,所以肯定只能是第一个位置配第二个位置的数,第三个配第四个这样子,然而第一个和第二个之间位置可以任意交换。

这里我们要用到一种叫做“cyclic swapping”的方法,先考虑把一个a[0]=0,a[1]=1,····,a[n] = n的数组打乱后的结果经过交换元素复原的步骤,设打乱后的数组为b,而其实用i = b[i]的方式找到的所有的i都会构成一个环,因为打乱后b里的元素也是唯一的,也就是说不存在i == b[i] && i == b[j] && i!=j的情况,这样一路找下去最多也就只能走N-1步就会回到初始值。用这种方法我们可以在这个数组里找到很多个环,而我们的最终目的就是让这个数组里只存在自环,也就是任意i == b[i]。

而对于任意一个环,其实我们只要交换其中两个元素的指向,就可以把它变成两个环(这个画个图就会比较清楚),这样反映到数组上也就是交换了两个元素,也不难看出无论怎么交换元素,都不可能有比这更快的产生环的办法了,所以交换的次数也就是这样一直交换直到只剩下自环,为了实现起来方便,我们不妨每次都找一个节点的下一个节点进行交换,这样总的交换次数同上所述并不会改变,所以具体的代码实现如下:

int miniSwapsArray(int[] row) {
    int ans = 0, N = row.length;

    for (int i = 0; i < N; i++) {
	for (int j = row[i]; i != j; j = row[i]) {
	    swap(row[i],row[j]);
	    ans++;
	}
    }

    return ans;
}

再回到我们的问题,这个问题和以上的问题其实很类似,但是最终我们的要求状态并不是i == b[i],而是旁边有一个配对数,我们假设每一个数i的位置为position[i],一个数的配对为partener[i],那么i的配对数为partener[i],配对数位置为position[partener[i]],这个位置的配对位置为partener[position[partener[i]]], 所以我们要求每个元素都满足 j == partenerposition[partener[rows[j]]]。这个函数因为是一一映射的复合函数,所以自然也是一一映射,也满足上述产生一个环的条件,所以实现方法类似:

class Solution {
public:
    int minSwapsCouples(vector<int>& row) {
        vector<int> partener(row.size());
        vector<int> position(row.size());
        int count = 0;
        for(int i = 0; i < row.size(); i++){
        	partener[i] = i%2==0 ? i+1 : i-1;
        	position[row[i]] = i;
        }
        for(int i = 0; i < row.size(); i++){
        	for(int j = partener[position[partener[row[i]]]]; i!=j; j=partener[position[partener[row[i]]]]){
        		swap(row[i],row[j]);
        		swap(position[row[i]],position[row[j]]);
        		count++;
        	}
        }
        return count;
    }
};

因为最多只会有N个环,拆分环的复杂度为O(1),所以总的复杂度自然为O(N)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值