题目:
实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 必须原地修改,只允许使用额外常数空间。
示例:
输入:1,2,3
输出:1,3,2
代码:
public class Test15 {
@Test
public void test(){
int[] nums = new int[]{1,5,1};
new Test15().nextPermutation(nums);
for (int num : nums) {
System.out.println(num);
}
}
public void nextPermutation(int[] nums) {
if (nums.length==1) {
return;
}
int max = nums[nums.length-1];
int i = nums.length-2;
while ( i>=0 && nums[i]>=max){
max =nums[i];
i--;
}
if (i==-1) {
Arrays.sort(nums);
return ;
}else{
max = nums[i];
int j = i+1;
while (j<nums.length && nums[j]>max){
j++;
}
int temp = nums[i];
nums[i] = nums[j-1];
nums[j-1] = temp;
Arrays.sort(nums,i+1,nums.length);
}
}
}