无聊啊 Next Permutation

不甚知道意义的题目,不过数组reverse值得复习一下哟

public class Solution {

    public void nextPermutation(int[] num) {

        //这个题目意义何在啊唉

        

        if (num==null || num.length==0) return;

        

        // 先找到第一个不符合从右往左一次变大的数 X

        int i=num.length-2;

        while(i>=0 && num[i]>=num[i+1]){

            i--;

        }

         

        

        // 从右开始找到第一个比X大的数num[j]

        if(i>=0){ 

        int j = num.length-1;

        while(j>i && num[j]<=num[i]){

            j--;

        } 

        swap(num, i, j);

        }

        

        reverse(num, i+1, num.length-1);

    }

    

    public void swap(int[] num, int i, int j){

        int t = num[i];

        num[i]= num[j];

        num[j] = t;

    }

    public void reverse(int[] num, int st, int end){

        while(st<end){

            swap(num, st, end);

            st++;

            end--;

        }

    }

}

 

你可能感兴趣的:(ext)