30. Next Permutation

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

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

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

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,1blog

» Solve this problemelement

---leetcode

---get

哎呦我去,這我哪寫的出來it

---io

public class Solution {
    public void nextPermutation(int[] num) {
        
        if(num.length<2)    return;
        
        // from right to left, find the first element
        // which violate the rule of increasing
        // called partition number
        int i = num.length-2;
        while(i>=0){
            if(num[i] < num[i+1]) break;
            i--;
        }
        
        if(i == -1){
            Arrays.sort(num);
            return;
        }
        
        
        int pn = num[i];
        
        // from the right to left, find the first element
        // which larger than partition number
        // called change number
        int j = num.length-1;
        while(num[j] <= pn){
            j--;
        }
        int cn = num[j];
        
        //swap pn and cn
        num[j] = pn;
        num[i] = cn;
        
        // sort all elements on the right of partition index
        Arrays.sort(num, i+1, num.length);
        
        
    }
}
相關文章
相關標籤/搜索