1053. Previous Permutation With One Swap

    xiaoxiao2024-12-12  12

    Given an array A of positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller than A, that can be made with one swap (A swap exchanges the positions of two numbers A[i] and A[j]).  If it cannot be done, then return the same array.

     

    Example 1:

    Input: [3,2,1] Output: [3,1,2] Explanation: Swapping 2 and 1.

    Example 2:

    Input: [1,1,5] Output: [1,1,5] Explanation: This is already the smallest permutation.

    Example 3:

    Input: [1,9,4,6,7] Output: [1,7,4,6,9] Explanation: Swapping 9 and 7.

    Example 4:

    Input: [3,1,1,3] Output: [1,1,3,3]

     

    Note:

    1 <= A.length <= 100001 <= A[i] <= 10000

    思路:之前有过类似的???就是从后往前遍历,直到出现 前面那个数比后面那个数大 就停止,比如到index为i的位置停止了,然后找到后面这段区间内小于A[i]的最大数(设index为j),然后交换ij位置的数即可

    class Solution(object): def prevPermOpt1(self, A): """ :type A: List[int] :rtype: List[int] """ # if tuple(A)==sorted(tuple(A)): return A i=len(A)-1 while i-1>=0 and A[i]>=A[i-1]: i-=1 if i==0: return A j=i i-=1 while j+1<len(A) and A[j+1]<A[i]: j+=1 A[i],A[j]=A[j],A[i] return A

     

    最新回复(0)