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

  • 相关阅读:
    给VPS装桌面
    GIT免密码PUSH
    验证码类
    Url几个常用的函数
    PHP--关于模板的原理和解析
    管理员权限执行批处理和静默执行regsvr32注册
    linux 维护常见场景小命令 (未完待续)
    批处理定时重启print打印服务,解决打印机异常队列堆积
    Linux----LVM扩容磁盘空间
    6、Samba 服务器配置
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13494712.html
Copyright © 2011-2022 走看看