[leedcode 31] Next Permutation

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

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

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

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

public class Solution {
    public void nextPermutation(int[] nums) {
        //本題的難點是如何找到下一個Permutation 
        //閱讀資料可知,^牢記這個形狀,首先找到最大的i,而且知足nums[i]<nums[i+1]
        //再從後向前找到第一個nums[i]<nums[k],k>i
        //swap() i和k
        //反轉i+1到n
        //注意遞減序列的判斷
        if(nums.length<=1) return;
        int len=nums.length-1;
        int i=0;
        for(i=len-1;i>=0;i--){
            if(nums[i]<nums[i+1])
               break;
        }
        if(i<0){//注意判斷是不是遞減數列
            reverse(nums,0,len);
            return;
        }
        int k=len;
        for(;k>i;k--){
            if(nums[i]<nums[k])
            break;
        }
        swap(nums,k,i);
        reverse(nums,i+1,len);
    }
    public void reverse(int nums[],int i,int j){
        while(i<j){
            swap(nums,i,j);
            i++;j--;
        }
        
    }
    public void swap(int nums[],int i,int j){
            int temp=nums[i];
            nums[i]=nums[j];
            nums[j]=temp;
    }
}
相關文章
相關標籤/搜索