31. Next Permutation
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
在当前序列中,从尾端往前寻找两个相邻元素,前一个记为first,后一个记为second,并且满足first 小于 second。然后再从尾端寻找另一个元素number,如果满足first 小于number,即将第first个元素与number元素对调,并将second元素之后(包括second)的所有元素颠倒排序,即求出下一个序列
example:
6,3,4,9,8,7,1
此时 first = 4,second = 9
从尾巴到前找到第一个大于first的数字,就是7
交换4和7,即上面的swap函数,此时序列变成6,3,7,9,8,4,1
再将second=9以及以后的序列重新排序,让其从小到大排序,使得整体最小,即reverse一下(因为此时肯定是递减序列)
得到最终的结果:6,3,7,1,4,8,9
public void nextPermutation(int[] nums) {
if (nums.length <= 1) {
return;
}
int i= nums.length-1;
for (; i >= 1 ; i--) {
if (nums[i] > nums[i - 1]) { //nums[i]是9,i是3
break;
}
}
if (i != 0) {
swap(nums,i - 1);
}
reverse(nums,i);
}
private void swap(int[] a,int i) {
for (int j = a.length - 1; j > i; j--) {
if(a[j] > a[i]) { //找到第一个比a[i]大的数,交换
int t = a[j];
a[j] = a[i];
a[i] = t;
break;
}
}
}
private void reverse(int[] a,int i){ //把后面的数字逆序排列
int first = i;
int last = a.length-1;
while (first < last) {
int t = a[first];
a[first] = a[last];
a[last] = t;
first ++;
last --;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix