1. 程式人生 > 實用技巧 >1053. Previous Permutation With One Swap

1053. Previous Permutation With One Swap

Given an arrayAof positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller thanA, that can bemade with one swap(Aswapexchanges 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. 1 <= A.length <= 10000
  2. 1 <= A[i] <= 10000
class Solution {
    public int[] prevPermOpt1(int[] A) {
        int n = A.length;
        int i = n - 1;
        while(i >= 1) {
            if(A[i - 1] <= A[i]) i--;
            else break;
        }
        if(i == 0) return A;
        i--;
        //System.out.print(i);
        int sec = A[i + 1], j = i + 2;
        
int secind = i + 1; while(j < n) { if(A[j] > sec && A[j] < A[i]) { sec = A[j]; secind = j; } j++; } int tmp = A[i]; A[i] = A[secind]; A[secind] = tmp; return A; } }

如果是升序就無解。1.從右往左找第一個破壞降序的,比如4321,2》1所以破壞了降序,2就是我們要換的數字,

2.從2右邊的數字中找出第一個比他小的,如果相同取左邊,交換即可。