Likou brushing notes: 765. Couples hold hands (violent solution, submissions with a speed exceeding 93.97%, submissions with a space exceeding 62%, difficult questions for the third day of the new year, this is it...)

topic:

Chapter 765: A Couple Holding Hands

N couples sit on 2N seats in a row and want to hold each other's hands. Calculate the minimum number of exchanges of seats so that each couple can sit side by side. Any two people can be selected for one exchange, and they can stand up and exchange seats.

People and seats are represented by integers from 0 to 2N-1. The lovers are numbered in sequence, the first pair is (0, 1), the second pair is (2, 3), and so on, the last pair is (2N- 2, 2N-1).

The initial seat row[i] of these couples is determined by the person who initially sat in the i-th seat.

Example 1:

Input: row = [0, 2, 1, 3]
Output: 1
Explanation: We only need to swap the positions of row[1] and row[2].

Example 2:

Input: row = [3, 2, 0, 1]
Output: 0
Explanation: No need to exchange seats, all couples can already hold hands.

Description:

len(row) is an even number and the value is in the range [4, 60].
It can be guaranteed that row is a complete permutation of the sequence 0...len(row)-1.

Problem solution ideas:

1. Observe the list given in the question. For element a, if it is an odd number, the couple must be a+1, and if it is an even number, the couple must be a-1.

2. traverse the list directly (the traversal step is 2), and determine whether the couple of element row[i] is row[i+1], if not, search in the remaining list elements, and exchange row[i+1 when found ] And row[j] (target couple).

Note: The traversal step is set to 2, because the i+1 position must meet the couple adjacent condition after the exchange, and there is no need to traverse the judgment again.

Problem solution python code:

class Solution:
    def minSwapsCouples(self, row: List[int]) -> int:
        # 定义函数获取一个数的另一半
        def getPerson(p):
            return p+1 if p%2==0 else p-1
            
        count,n = 0,len(row)
        for i in range(0, n-1, 2):
            t = getPerson(row[i])
            if t!=row[i+1]:  # 如果row[i+1]的值不是row[i]的情侣,则对剩下的人进行查找
                for j in range(i+1, n):
                    if row[j]==t:   # 找到后二者交换
                        row[i+1],row[j] = row[j],row[i+1]
                        count += 1
        # print(row)
        return count

Insert picture description here

Author: a-qing-ge
Links: https://leetcode-cn.com/problems/couples-holding-hands/solution/bao-li-jie-fa-su-du-chao-9397de-ti-jiao-0j8cf /
Source: LeetCode https://leetcode-cn.com/problems/couples-holding-hands/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/113811183