Next Permutation
来源:互联网 发布:质量数据分析管理办法 编辑:程序博客网 时间:2024/06/18 18:33
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
思路就是从右往左扫,如果递增就继续,如果下一个数小于当前数num[cur],则再扫一遍找到比num[cur-1]大且比其他数小的下标。比如:1,3,4,2 搜到4 的时候发现下一个数字3比他小,那么就再从右往左扫一遍,找到比3大且比其他小的下标,这就是4的下标。调换num[cur-1] 和 num[minIndex],然后对剩下的右半边排列。
2014.11 update: 最后一步不要使用Arrays.sort,而是直接左右交换即可排序。
public void nextPermutation(int[] num) { int peakInd = 0; for (int i = num.length-1; i > 0; i--) { if (num[i] > num[i-1]) { peakInd = i; break; } } if (peakInd > 0) { int swapInd = num.length-1; while (swapInd > peakInd-1 && num[swapInd] <= num[peakInd-1]) { swapInd--; } int tmp = num[swapInd]; num[swapInd] = num[peakInd-1]; num[peakInd-1] = tmp; } int left = peakInd; int right = num.length-1; while (left < right) { int tmp = num[left]; num[left] = num[right]; num[right] = tmp; right--; left++; } }
public void nextPermutation(int[] num) { int n = num.length; if (n <= 1) { return; } int cur = n-1; while (cur >= 1 && num[cur-1]>= num[cur]) { cur--; } if (cur == 0) { Arrays.sort(num); return; } int min = Integer.MAX_VALUE; int minIndex = n-1; for (int i = n-1; i >= cur; i--) { if (num[i] > num[cur-1] && num[i] < min) { min = num[i]; minIndex = i; } } int tmp = num[cur-1]; num[cur-1] = num[minIndex]; num[minIndex] = tmp; Arrays.sort(num, cur, n); }
0 0
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Add Two Numbers 看着简单,其实各种奇葩情况需要考虑。。。
- 《红孩儿引擎内功心法修练与Cocos2d-x》之结点系统(场景,层,精灵)(精)
- vim显示行号、语法高亮、自动缩进的设置
- PROC系列之---/proc/pid/stat
- 访问者模式之C++实现
- Next Permutation
- top命令详解
- uva 10012
- Merge Intervals 合并区间
- CF377B Preparing for the Contest [贪心+优先队列]
- liunx下lnmp环境安装
- A20内核编译错误undefined reference to `hwmon_device_register'
- 等腰三角形
- centos 打开or关闭防火墙