31. Next Permutation

class Solution {
    public void nextPermutation(int[] nums) {
        int i=nums.length-1;
        while(i>0&&nums[i-1]>=nums[i])i--;
        if(i==0)
        {
            Arrays.sort(nums);
            return;            
        }

        int j=i-1;
        i=nums.length-1;
        while(nums[j]>=nums[i])i--;
        swap(j, i, nums);
        
        i=nums.length-1;
        j++;
        while(j<i)
        {
            swap(i, j, nums);
            i--;
            j++;
        }
    }
    private void swap(int i, int j, int[] nums)
    {
        int tmp=nums[i];
        nums[i]=nums[j];
        nums[j]=tmp;
    }
}

 

posted @ 2017-09-23 07:33  Weiyu Wang  阅读(117)  评论(0编辑  收藏  举报