# 31. Next Permutation --LeetCode

1 篇文章 0 订阅

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 void nextPermutation(int[] nums) {
int[] arr = new int[nums.length];
for(int i =0;i<arr.length;i++)
arr[i]=0;
int length=0;
for(int i=nums.length-1;i>=0;i--,length++)
{
if(i!=nums.length-1&&nums[i+1]>nums[i])
{
arr[length] = nums[i];
length++;
break;
}
arr[length] = nums[i];
}

	        int temp=Integer.MAX_VALUE;
int index=length-1;
for(int i=0;i<length;i++)
{
if(arr[i]<temp&&arr[i]>arr[length-1])
{
temp=arr[i];
index=i;
}
}
int tempNum = arr[index];
nums[nums.length-index-1] = nums[nums.length-length];
nums[nums.length-length] = tempNum;
Arrays.sort(nums,nums.length-length+1,nums.length);

    public void nextPermutation(int[] nums) {
int[] arr = new int[nums.length];
for(int i =0;i<arr.length;i++)
arr[i]=0;
int length=0;
for(int i=nums.length-1;i>=0;i--,length++)
{
if(i!=nums.length-1&&nums[i+1]>nums[i])
{
arr[length] = nums[i];
length++;
break;
}
arr[length] = nums[i];
}
int[] tempArr = Arrays.copyOf(nums,nums.length);
Arrays.sort(tempArr);
if(Arrays.equals(tempArr, arr))
{
Arrays.sort(nums);
return;
}
int temp=Integer.MAX_VALUE;
int index=length-1;
for(int i=0;i<length;i++)
{
if(arr[i]<temp&&arr[i]>arr[length-1])
{
temp=arr[i];
index=i;
}
}
int tempNum = arr[index];
nums[nums.length-index-1] = nums[nums.length-length];
nums[nums.length-length] = tempNum;
Arrays.sort(nums,nums.length-length+1,nums.length);
}

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 1
评论
07-03 119
01-16 2200
08-11 485
08-11 525

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