题目描述:
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;
}
}
本文介绍了一个经典算法问题“下一个排列”的解决方案。该问题要求在给定一组整数的情况下,找到下一个字典序更大的排列。如果不存在这样的排列,则将其变为最小的排列(即升序排列)。文章详细介绍了算法的实现思路,并提供了完整的Java代码示例。
536

被折叠的 条评论
为什么被折叠?



