Next Permutation

来源:互联网 发布:数据时代的坏 编辑:程序博客网 时间:2024/05/16 01:02

题目描述:
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

解题思路,从后向前循环,直到找到前一个数比后一个数小的时候,即a(i-1)< a(i),然后将a(i),a(i+1)…a(n-1)中比a(i)大得最少的数找出来,互换位置,然后将后面的数倒序即可。

如2,4,3,2
当i=1时a(0)< a(1),找到3比2大,将第一个2和3互换位置成3,4,2,2。然后将后面的4,2,2倒序即成3,2,2,4。

代码如下:

public void nextPermutation(int[] nums) {    int n=nums.length;    int i=n-1;    while(i>0){        if(nums[i-1]>=nums[i]){            i--;        }else{            int j=n-1;            while(j>=i&&nums[j]<=nums[i-1]){                j--;            }            int temp=nums[i-1];            nums[i-1]=nums[j];            nums[j]=temp;            reverseArrayFromIndex(nums, i);            return ;        }    }    reverseArrayFromIndex(nums, 0);}   public void reverseArrayFromIndex(int[] nums,int start){    int low=start,high=nums.length-1;    int temp=0;    while(low<high){        temp=nums[low];        nums[low++]=nums[high];        nums[high--]=temp;    }}
0 0
原创粉丝点击