Python 如何找到排序列表的最小移动次数?
在一个由N个不同整数组成的给定列表中,我希望通过按升序将一个元素移动到列表的末尾,找到排序列表所需的最小移动次数Python 如何找到排序列表的最小移动次数?,python,python-3.x,sorting,Python,Python 3.x,Sorting,在一个由N个不同整数组成的给定列表中,我希望通过按升序将一个元素移动到列表的末尾,找到排序列表所需的最小移动次数 输出为:1 4 3 2 5[1,3,2,5,4]1[1,2,5,4,3]2[1,2,4,3, 5] 3[1,2,3,5,4]4[1,2,3,4,5]5无 让我们首先观察以下事实 要获得最小步数,一个数字只能移动一次 较小的数字必须先移动到左边 如果数字右边的数字较小,则该数字不合适 考虑到这一点,我们可以从右向左遍历列表,并跟踪非递减的数字(3)。通过对这些数字(2)进行排序,我们得
输出为:1 4 3 2 5[1,3,2,5,4]1[1,2,5,4,3]2[1,2,4,3, 5] 3[1,2,3,5,4]4[1,2,3,4,5]5无
让我们首先观察以下事实
def end_sort_steps(lst):
steps = 0
right_min = max(lst)
for n in reversed(lst):
if n >= right_min:
# Then the number must be moved
steps += 1
else:
# Otherwise it is the smallest number seen yet
right_min = n
return steps
输出是:1 4 3 2 5[1,3,2,5,4]1[1,2,5,4,3]2[1,2,4,3,5]3[1,2,3,5,4]4[1,2,3,4,4,5]5非应该是
[1 4 3 2 5]->[1,4,2,5,3]->[1,2,5,3,4]->[1,2,3,3,3,5]
?
def end_sort_steps(lst):
steps = []
right_min = max(lst)
for n in reversed(lst):
if n >= right_min:
# Then the number must be moved
steps.append(n)
else:
# Otherwise it is the smallest number seen yet
right_min = n
return sorted(steps)
print(end_sort_steps([1, 4, 3, 2, 5])) # [3, 4, 5]
# This corresponds to the steps:
# [1, 4, 3, 2, 5] -> [1, 4, 2, 5, 3] -> [1, 2, 5, 3, 4] -> [1, 2, 3, 4, 5]
def end_sort_steps(lst):
steps = 0
right_min = max(lst)
for n in reversed(lst):
if n >= right_min:
# Then the number must be moved
steps += 1
else:
# Otherwise it is the smallest number seen yet
right_min = n
return steps