Leetcode: Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

public class Solution {
    public void nextPermutation(int[] num) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(num==null||num.length<=1){
            return;
        }

        int i=num.length-2;
        while(i>=0 && num[i]>=num[i+1]){
            i--;
        }
        if(i==-1){
            int m = 0;
            int n = num.length-1;
            while(m<n){
                swap(num,m,n);
                m++;
                n--;
            }

        }else{
            int minIndex = i+1;
            for(int j=minIndex+1;j<num.length;j++){
                if(num[j]>num[i] && num[j]<num[minIndex]){
                    minIndex=j;
                }
            }
            swap(num,i,minIndex);

            for(int k=i+1;k<num.length;k++){
                minIndex = k;
                for(int l=k+1;l<num.length;l++){
                    if(num[l]<num[minIndex]){
                        minIndex=l;
                    }
                }
                swap(num,k,minIndex);
            }
        }

    }

    public void swap(int[] num, int i, int j){
        int tmp = num[i];
        num[i] = num[j];
        num[j] = tmp;
    }

}
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *