LeetCode Next Permutation
2015-06-25 09:52
549 查看
Description:
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.
Solution:
这里我们可以假设有这么几个数字:d c b a
先忽略相等的情况,那么可以发现
if a > b
then switch a, b
else // (a<b)
if b > c
then b,a,c (a<c) or b,c,a (c<a)
else // a<b<c
then ...
综上就是这么几个结论:
找到从后往前第一个增长的点,假设增长的点位ascendingPoint,简称ap。(这里因为代码方便,我设置的是ap-1,ap是增长两个前后点)。
那么需要把所有[ap,length()-1]的点中找到比ap-1点的数值大的 最小值(大于ap-1的最小点),这个最小点就是变换之后在ap-1这个位置的数值,后面的排序即可。
如果ap=0,就表示所有的点递减,那么按照题目要求重新排序就好。
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.
Solution:
这里我们可以假设有这么几个数字:d c b a
先忽略相等的情况,那么可以发现
if a > b
then switch a, b
else // (a<b)
if b > c
then b,a,c (a<c) or b,c,a (c<a)
else // a<b<c
then ...
综上就是这么几个结论:
找到从后往前第一个增长的点,假设增长的点位ascendingPoint,简称ap。(这里因为代码方便,我设置的是ap-1,ap是增长两个前后点)。
那么需要把所有[ap,length()-1]的点中找到比ap-1点的数值大的 最小值(大于ap-1的最小点),这个最小点就是变换之后在ap-1这个位置的数值,后面的排序即可。
如果ap=0,就表示所有的点递减,那么按照题目要求重新排序就好。
import java.util.Arrays; public class Solution { public void nextPermutation(int[] nums) { int ascendingPoint = getAscendingPoint(nums); if (ascendingPoint == 0) { Arrays.sort(nums); } else { int minBigger = Integer.MAX_VALUE; for (int i = nums.length - 1; i >= ascendingPoint; i--) { if (nums[i] > nums[ascendingPoint - 1] && nums[i] < minBigger) { minBigger = nums[i]; nums[i] = nums[ascendingPoint - 1]; nums[ascendingPoint - 1] = minBigger; } } Arrays.sort(nums, ascendingPoint, nums.length); } } int getAscendingPoint(int nums[]) { for (int i = nums.length - 1; i > 0; i--) if (nums[i] > nums[i - 1]) return i; return 0; } }
相关文章推荐
- Qt QScrollBar qss 美化样例
- Xshell常用命令备忘
- jquery分页组件(每页显示多少条)
- gulp入门~
- CXF和Spring整合
- qt 获取 xml
- 网络联调
- js如何实现继承
- Java实现ftp上传文件、文件夹
- django+uwsgi报错libgcc_s.so.1 must be installed for pthread_cancel to work
- JVM GC日志和内存DUMP参数配置
- springmvc中以一个页面作为响应返回给ajax
- DateFormat
- Dijkstra(优先队列)
- Git版本控制软件结合GitHub从入门到精通常用命令学习手册
- ByteBuffer的mark、position、limit、flip、reset,get方法介绍
- [12 Jun 2015 ~ 18 Jun 2015] Deep Learning in arxiv
- BellmanFord
- session保持会话可能存在账号安全问题
- Android使用j4lChartAndroid插件绘制3D饼图