博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode | Next Permutation
阅读量:6975 次
发布时间:2019-06-27

本文共 1866 字,大约阅读时间需要 6 分钟。

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

分析了一下,得出有以下规律,accepted。大体思路和网上一样。红色部分是网上的解法。

1. 从右往左扫,找到第一个不符合num[i]>=num[i+1]的数;

2. 然后从[i+1...n-1]中找到比num[i]大的最小数num[j];这里我直接找大于num[i]的最小值了;其实因为[i+1..n-1]是递减的,可以从右往左扫,找到第一个数就退出就行了。

3. 交换num[j]和num[i];交换之后,仍然会保证[i+1...n-1]是递减的。

4. 对[i+1...n-1]进行排序;因为[i+1...n-1]是递减的,直接reverse就可以了,不需要排序。 

5. 如果找到的数i<0,也就是整个序列都是递减的,那么直接排序就行;同样可以用reverse

1 class Solution { 2 public: 3     void nextPermutation(vector
&num) { 4 int i; 5 for (i = num.size() - 2; i >= 0; --i) { 6 if (num[i] >= num[i + 1]) continue; 7 int minIndex = i + 1; 8 for (int j = i + 1; j < num.size(); ++j) { 9 if (num[j] > num[i] && num[j] < num[minIndex]) minIndex = j;10 }11 swap(num[i], num[minIndex]);12 sort(num.begin() + i + 1, num.end());13 break;14 }15 if (i < 0) sort(num.begin(), num.end());16 }17 };

不过因为可以不用写reverse的代码,直接用sort看起来简洁得多。重构了一下代码就是:

1 class Solution { 2 public: 3     void nextPermutation(vector
&num) { 4 int i, j; 5 for (i = num.size() - 2; i >= 0 && num[i] >= num[i + 1]; --i); 6 if (i >= 0) { 7 for (j = num.size() - 1; j > i && num[j] <= num[i]; --j); 8 swap(num[i], num[j]); 9 } 10 sort(num.begin() + i + 1, num.end());11 }12 };

 

转载于:https://www.cnblogs.com/linyx/p/3734451.html

你可能感兴趣的文章
XenApp_XenDesktop_7.6实战篇之八:申请及导入许可证
查看>>
oracle--查看表空间大小以及修改表空间大小
查看>>
CSS float浮动的深入研究、详解及拓展(二)
查看>>
Java Web的Maven项目中Properties文件的使用(2)
查看>>
终于申请博客了
查看>>
foj2024
查看>>
linux之shell脚本学习篇一
查看>>
hdu(1596)
查看>>
[毕业生的商业软件开发之路]C#类型样式
查看>>
华为巨资收购为云计算趟平道路?
查看>>
java继承中的一些该注意的问题
查看>>
epoll/select
查看>>
Configure,Makefile.am, Makefile.in, Makefile文件之间关系
查看>>
NLP常用工具
查看>>
学习PHP ?
查看>>
WinAPI: Arc - 绘制弧线
查看>>
动态规划和分治法,贪心算法以及递归的再一次深刻理解和体会
查看>>
Direct2D (15) : 剪辑
查看>>
WinAPI: 钩子回调函数之 SysMsgFilterProc
查看>>
WinAPI: SetRect 及初始化矩形的几种办法
查看>>