Участник:Plague rat/Previous Permutation With One Swap

Материал из DISCOPAL
Перейти к: навигация, поиск

https://leetcode.com/problems/previous-permutation-with-one-swap/

class Solution:
    def prevPermOpt1(self, A: List[int]) -> List[int]:
        left = -1
        for i in range(len(A) - 1, -1, -1):
            if i > 0 and A[i - 1] > A[i]:
                left = i - 1
                break
        if left == -1:
            return A
 
        right = 10001
        _max = -1
        for j in range(left + 1, len(A)):
            if A[j] < A[left] and A[j] > _max:
                _max = A[j]
                right = j
 
        A[left], A[right] = A[right], A[left]
        return A