LeetCode:1053。 1つのスワップによる以前の順列
Leetcode 1053 Previous Permutation With One Swap
与えられた配列A
正の整数(必ずしも区別できるとは限りません)の場合、A
よりも小さい辞書式順序で最大の順列を返します。 1回の交換で作成 (に スワップ 2つの数値の位置を交換しますA[i]
とA[j]
)。それができない場合は、同じ配列を返します。
例1:
1 <= A.length <= 10000
例2:
1 <= A[i] <= 10000
例3:
class Solution { public: vector prevPermOpt1(vector& A) { int n = A.size() vectordp dp = A for(int i=n-1 i>=0 --i){ int max_val = 0 int max_idx = -1 for(int j=i+1 j 例4:
Input: [3,2,1] Output: [3,1,2] Explanation: Swapping 2 and 1.
注意:
Input: [1,1,5] Output: [1,1,5] Explanation: This is already the smallest permutation.
Input: [1,9,4,6,7] Output: [1,7,4,6,9] Explanation: Swapping 9 and 7.
考える:後ろから前を向いて、現在の最大値の後ろの位置を探すことは、2つの場所の交換価値である位置よりも小さいです
Input: [3,1,1,3] Output: [1,3,1,3] Explanation: Swapping 1 and 3.