小C的排列构造问题

79 阅读1分钟

可以使用栈的数据结构将n个数从大到小进栈,因为b 的字典序尽可能小,所以我们每次对栈顶的数操作,如果合法就直接赋值,不合法再弹出栈顶的数然乎把不合法的重新入栈,同时最后一个数单独讨论。


import java.util.Arrays;
import java.util.Stack;
public class Main {
    public static int[] solution(int n, int[] a) {
        Stack<Integer> st=new Stack<>();
        int i,j;
        for(i=n;i>0;i--){
            st.push(i);
        }
        int[] ans=new int[n];
       for(i=0;i<n;i++){
           j=st.pop();
           if(j!=a[i]){
               ans[i]=j;
           }else if(i==n-1){
               ans[i]=ans[i-1];
               ans[i-1]=j;
           }else {
               ans[i]=st.pop();
               st.push(j);
           }

       }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.equals(solution(3, new int[]{1, 2, 3}), new int[]{2, 3, 1}));
        System.out.println(Arrays.equals(solution(4, new int[]{3, 1, 2, 4}), new int[]{1, 2, 4, 3}));
        System.out.println(Arrays.equals(solution(5, new int[]{5, 3, 1, 4, 2}), new int[]{1, 2, 3, 5, 4}));
    }
}