给定一个若干整数的排列,给出按正数大小进行字典序从小到大排序后的下一个排列。
如果没有下一个排列,则输出字典序最小的序列。
样例
左边是原始排列,右边是对应的下一个排列。
1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
1、先从右到左找到第一个不属于非最大字典序排列的元素L,若没找到,即原序列为最大字典序,直接排序返回
2、再从右到左找到第一个比L大的元素R,并将其和L交换值;
3、将L后的子序列变为最小子序列。返回
public class Solution {
/**
* @param nums: an array of integers
* @return: return nothing (void), do not return anything, modify nums in-place instead
*/
public void nextPermutation(int[] nums) {
// write your code here
int L = nums.length-2;
while(L>=0&&nums[L] >= nums[L+1])
--L;
if(L<0){
Arrays.sort(nums);
return;
}
// find the max which lower than nums[L]
int R = nums.length-1;
while(nums[R] <= nums[L])
--R;
nums[R] += nums[L];
nums[L] = nums[R] - nums[L];
nums[R] = nums[R] - nums[L];
int[] t = new int[nums.length-L-1];
for(int i=0;i<t.length;++i)
t[i] = nums[i+L+1];
Arrays.sort(t);
for(int i=0;i<t.length;++i)
nums[i+L+1] = t[i];
return ;
}
}