检查数组是否可以在 Python 中用一次交换进行排序
假设,我们提供了一个包含整数元素的数组。如果我们只能执行一次交换操作,我们必须找出数组中的值是否可以按非递减顺序排序。如果可能,我们说可以做到,否则就不能。
因此,如果输入类似于input_list=[7,8,12,10,11,9],那么输出将是“可以完成”
为了解决这个问题,我们将按照以下步骤操作-
temp_list:=列表input_list的副本
对列表temp_list进行排序
交换计数:=0
对于范围0到input_list大小的i,请执行
交换计数:=交换计数+1
如果input_list[i]与temp_list[i]不同,则
如果swap_count与0相同或swap_count与2相同,则
返回真
否则,
返回错误
让我们看看以下实现以获得更好的理解-
示例
from copy import deepcopy def solve(input_list): temp_list = deepcopy(input_list) temp_list.sort() swap_count = 0 for i in range(len(input_list)): if input_list[i] != temp_list[i]: swap_count += 1 if swap_count == 0 or swap_count == 2: print("Can be done") else: print("Can't be done") input_list = [7, 8, 12, 10, 11, 9] solve(input_list)
输入
[7, 8, 12, 10, 11, 9]输出结果
Can be done