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
题意:给定一个全排列,求下一组全排列。
分类:数组
解法1:在当前序列中,从尾端往前寻找两个相邻元素,前一个记为*i,后一个记为*ii,并且满足*i < *ii。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第ii个元素之后(包括ii)的所有元素颠倒排序,即求出下一个序列了。
public class Solution {
public void nextPermutation(int[] nums) {
if(nums.length<=1) return;
int i = nums.length-1;
while(i>0){//倒序找到第一对逆序数
if(nums[i]>nums[i-1]){
break;
}
i--;
}
if(i>0){//找到逆序对
int j = nums.length-1;
i--;//指向逆序对的第一个元素
while(j>=0){//找到大于nums[i]的第一个元素
if(nums[j]>nums[i]){
break;
}
j--;
}
int temp = 0;//交换i,j
temp = nums[i];
nums[i]= nums[j];
nums[j] = temp;
reverse(nums, i+1, nums.length-1);//翻转
}else{//没有找到逆序对
reverse(nums, 0, nums.length-1);
}
System.out.println(Arrays.toString(nums));
}
public void reverse(int[] nums,int low,int high){
int temp = 0;
while(low<high){
temp = nums[low];
nums[low] = nums[high];
nums[high] = temp;
low++;high--;
}
}
}