31. Next Permutation
来源:互联网 发布:淘宝售后多长时间 编辑:程序博客网 时间:2024/06/05 15:09
这是别人的解释,自己打的代码,在当前序列中,从尾端往前寻找两个相邻元素,前一个记为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
还有特殊情况就是i==0
public class Solution { public void nextPermutation(int[] nums) { if(nums.length<=1)return; int i = nums.length-1; for(;i>=1;i--){ if(nums[i-1]<nums[i]) break; } int first = i-1; int second = i; if(i!=0){//3,2,1 → 1,2,3 这种是i==0的情况,就是直接翻转 int j =nums.length-1; for(;j>i-1;j--){ if(nums[j]>nums[first])break; } swap(nums,first,j); } reverse(nums,second,nums.length-1); } private void swap(int[]nums,int i,int j){ int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } private void reverse(int []nums,int start,int end){ int i=start; int j=end; while(i<j){ swap(nums,i,j); i++; j--; } }}
0 0
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- 31. Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- 31. Next Permutation
- Leetcode 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- android自定义ViewGroup之瀑布流FlowLayout 简洁明了 支持padding和margin 100行代码搞定
- テクニカルアーティストに必要な資料集めようぜ!
- 微信公众号开发——模板消息
- 交叉编译libxml2到ARM平台
- TweenJS
- 31. Next Permutation
- 百度地图定位之获取所在城市
- 翻转链表
- Node.js 异步异常的处理与domain模块解析
- Ubuntu通过apt-get install安装mysql后pdo_mysql无法连接的解决方法
- 使用C语言进行面向对象的开发--GObject入门[7]
- 1613-3-傅溥衍 总结《2016年10月18日》【连续第十八天总结】
- iOS下ffmepg开发的一些参考资料汇总
- 让你的Mac不在依赖于ssh软件