class Solution: def nums(self,num): if num % 2: return num - 1 else: return num + 1 def minSwapsCouples(self, row: List[int]) -> int:
res = 0 #是否需要交换
change = False length = len(row) # 两个正确的值 两个 错误的值 if length <= 2: return row
#左右两个定点指针 right ,left = 0, length - 1 curr, another = right + 1 ,left - 1 tmp = None while curr < another: # 说明是当前位是偶数 right_right = self.nums(row[right])
#如果左针的值 是右针的值的情侣
if right_right == row[left]: row[right+1], row[left] = row[left], row[right+1] res += 1 continue left_right = self.nums(row[left]) #有一个问题是 我遍历左边的时候 如果 出现了左边需要的值的时候怎么办 用一个tmp记录他 while row[curr] != right_right: change = True if row[curr] == left_right: tmp = curr curr += 1 # 必然已经找到了 正确的值 if change:
#当左针的值刚好是右针的情侣占位 且被交换走的情况 if tmp == right+1: tmp = curr row[right+1], row[curr] = row[curr], row[right+1] res += 1 change = False # 说名前一个指针在移动时 并没有找到正确位置 # 指针移动一下位置 right += 2 curr = right + 1 if right == another: break while row[another] != left_right and another > curr - 2: if row[left-1] == left_right: break change = True if tmp: another,tmp = tmp,None break another -= 1 if change: change = False row[left-1],row[another] = row[another],row[left-1] res += 1 left -= 2 another = left - 1 return res
修改后的代码如上:
修改前的代码如下:
class Solution: def minSwapsCouples(self, row: List[int]) -> int: def find_another(n): if n % 2 == 0: return n + 1 else: return n - 1 c = 0 for i in range(0, len(row), 2): p1 = row[i] p2 = find_another(p1) if row[i+1] != p2: j = row.index(p2) row[i+1], row[j] = row[j], row[i+1] c += 1 return c
两相比较修改过程:
虽然结果并未想像中的那么好,但是修改的过程还是蛮愉悦的,特此记录一番!