其他分享
首页 > 其他分享> > 1053. Previous Permutation With One Swap

1053. Previous Permutation With One Swap

作者:互联网

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,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右边的数字中找出第一个比他小的,如果相同取左边,交换即可。

标签:1053,int,Explanation,Output,Swap,Permutation,Input,secind,Example
来源: https://www.cnblogs.com/wentiliangkaihua/p/13494712.html