leetcode-31 Next Permutation
来源:互联网 发布:阿里云创建快照 编辑:程序博客网 时间:2024/06/05 19:09
31 Next Permutation
这道题让我们求下一个排列顺序,有题目中给的例子可以看出来,如果给定数组是降序,则说明是全排列的最后一种情况,则下一个排列就是最初始情况。我们再来看下面一个例子,有如下的一个数组
1 2 7 4 3 1
下一个排列为:
1 3 1 2 4 7
那么是如何得到的呢,我们通过观察原数组可以发现,如果从末尾往前看,数字逐渐变大,到了2时才减小的,然后我们再从后往前找第一个比2大的数字,是3,那么我们交换2和3,再把此时3后面的所有数字转置一下即可,步骤如下:
1 2 7 4 3 1
1 2 7 4 3 1
1 3 7 4 2 1
1 3 1 2 4 7
代码:
class Solution {public: void nextPermutation(vector<int>& nums) { if(nums.empty()) return; int i; for(i = nums.size()-1;i>0;i--) if(nums[i-1]<nums[i]) break; reverse(nums.begin()+i,nums.end());//先倒转 if(i==0) return; auto itr = upper_bound(nums.begin()+i, nums.end(), nums[i-1]);//二分查找优化查找效率 swap(nums[i-1], *itr); return; }};
阅读全文
0 0
- LeetCode 31: Next Permutation
- [leetcode 31] Next Permutation
- LeetCode(31) Next Permutation
- LeetCode---(31) Next Permutation
- leetcode 31 -- Next Permutation
- leetcode 31: Next Permutation
- LeetCode(31) Next Permutation
- LeetCode-31 Next Permutation
- Leetcode#31||Next Permutation
- LeetCode 31: Next Permutation
- LeetCode(31)-Next Permutation
- leetcode(31) Next Permutation
- LeetCode 31 - Next Permutation
- 【leetcode】【31】Next Permutation
- LeetCode-31:Next Permutation
- leetcode (31) Next Permutation
- LeetCode 31 Next Permutation
- leetcode-31-Next Permutation
- uva 232
- Java nio
- 冒泡排序原则排序
- [HDU]-6060 RXD and dividing
- Java基本数据类型传值,引用数据类型传引用
- leetcode-31 Next Permutation
- 汇编语言入门
- 使用HashSet方法实现多个对象的遍历
- File类 文件入门 IO流
- 个人宏工作簿PERSONAL.XLSB 保存位置 启动加载项
- 在Android Studio中如何安装Genymotion模拟器插件
- wifi(rtl8188eu)移植及调试笔记
- MySQL数据库优化
- Android 彻底弄懂Activity四大启动模式 和taskAffinity属性详解 intentFlag 图文解析