Python中的下一个排列
假设我们要实现下一个置换方法,该方法将数字重新排列到字典上数字的下一个更大置换中。如果无法进行这种排列,则此方法会将其重新排列为最低可能的顺序(实际上是按升序排序)。替换必须就位,并且不要使用任何额外的内存。例如,如果“输入”在左栏中,而其相应的输出在右栏中。
1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1
让我们看看步骤-
找到:=否,我:=数组的长度–2
当我>=0时
如果A[i]<A[i+1],则发现:=True,并终止循环
使我增加1
如果找到:=false,则对数组A进行排序,
除此以外
m:=从索引i+1,从A和从当前元素A[i]中找到最大元素索引
交换元素A[i]和A[m]
将所有元素从i+1反转到A的末尾
让我们看下面的实现以更好地理解-
示例
class Solution(object):
def nextPermutation(self, nums):
found = False
i = len(nums)-2
while i >=0:
if nums[i] < nums[i+1]:
found =True
break
i-=1
if not found:
nums.sort()
else:
m = self.findMaxIndex(i+1,nums,nums[i])
nums[i],nums[m] = nums[m],nums[i]
nums[i+1:] = nums[i+1:][::-1]
return nums
def findMaxIndex(self,index,a,curr):
ans = -1
index = 0
for i in range(index,len(a)):
if a[i]>curr:
if ans == -1:
ans = curr
index = i
else:
ans = min(ans,a[i])
index = i
return index
ob1 = Solution()print(ob1.nextPermutation([1,2,5,4,3]))输入值
[1,2,5,4,3]
输出结果
[1, 3, 2, 4, 5]