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 Next_Permutation {
	public static int Min(int array[],int index,int num)
	{
		int low=index;
		for(int i=index+1;i<array.length;i++)
		{
			if(array[low]>array[i]&&array[i]>num)
			{
				low=i;
			}
		}
		return low;
	}
	public static void Permutation(int array[])
	{
		for(int i=array.length-1;i>=1;i--)
		{
			if(array[i]>array[i-1])
			{
				int low=Min(array,i,array[i-1]);
				array[i-1]=array[i-1]^array[low];
				array[low]=array[low]^array[i-1];
				array[i-1]=array[i-1]^array[low];
				Arrays.sort(array,i,array.length);
				break;
			}
			if(i==1)
			{
				Arrays.sort(array);
			}
		}
		System.out.println(Arrays.toString(array));
	}
	public static void main(String[] args) {
		int array[]={2,3,6,5,4,1};
		Permutation(array);
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值