情侣换座位手牵手的题目。
思想有点像打气球那个题目:处理好当下的问题,慢慢往后遍历,以后的问题也会变得很顺利,回头还会发现这其实就是最好的方法。
题目描述
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
Example 1
1 | Input: row = [0, 2, 1, 3] |
Explanation: We only need to swap the second (row[1]) and third (row[2]) person.
Example 2
1 | Input: row = [3, 2, 0, 1] |
Explanation: All couples are already seated side by side.
解题思路
贪心算法。
详细解释
如果我们仔细看就会发现,其实我们在判断的时候只要确定了两个数中的一个,那么另外一个数是多少其实就是已经确定好了的,然后我们将这个数本身所在的位置替换掉就可以了。比如说下面的例子,第一个元素是5,那么第二个元素必然是6,我们只要找到6,然后将6本身所在的位置的数字替换成第二个元素本身的元素4就可以了。
以题目中的某个用例来进行说明
1 | 初始数组:[5,6,4,0,2,1,9,3,8,7,10,11] |
巧妙之处
- 大道至简,大智若愚。从头开始,每次都做好当前元素的判断,那么后面的元素都会依次的处理好。
- 对于当前位置要进行奇偶判断,因为不确定配偶的左右情况,所以要自行判断。
- 要会使用stl中的各种比较巧妙的方法,比如本题目中用到的find和distance。
解题代码
1 | class Solution { |
以上,本题结束!