Topics are as follows:
Given an array
A
of positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller thanA
, that can be made with one swap (A swap exchanges the positions of two numbersA[i]
andA[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,3,1,3] Explanation: Swapping 1 and 3.
Note:
1 <= A.length <= 10000
1 <= A[i] <= 10000
Problem-solving ideas: to find lexicographically less than their maximum value, as follows: A forward traversal from, for any A [I], find themselves in a less than [i + 1, A.length] interval the maximum value, if such a value can be found, then the two switching elements, that is, after the exchange a lexicographically less than their maximum value. How to find [+ 1, A.length i] interval smaller than themselves to find the maximum? Arrays can put all the values within the interval stored in an orderly, you can look through the half.
code show as below:
class Solution(object): def prevPermOpt1(self, A): """ :type A: List[int] :rtype: List[int] """ import bisect dic = {} val_list = [] for i in range(len(A)-1,-1,-1): inx = bisect.bisect_left(val_list,A[i]) inx -= 1 if inx >= 0 and inx < len(val_list): A[i], A[dic[val_list[inx]]] = A[dic[val_list[inx]]], A[i] break if A[i] not in dic: bisect.insort_left(val_list,A[i]) dic[A[i]] = i return A