[LeetCode]Next Permutation(!!!)
来源:互联网 发布:知乎 套路钓鱼 编辑:程序博客网 时间:2024/05/09 06:36
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
题目的意思是求下一个回文数,如果是最大的那个就变成最小的那个
首先我们考虑下从最大的数,变成最小的数,就是依次交换最高位和最低位。
其他情况比如 236541,我们从后往前寻找,找到第一个非递减的数,这里是3,然后从3开始往后寻找比3大的最小的数(实际上就是比3大的最后一个数,这里是4,将4和3交换后为246531然后将6531翻转即可241356
class Solution {public: void nextPermutation(vector<int>& nums) { int i = nums.size()-2; //从非最后一个元素开始,找非递减的第一个数 int j; while(nums[i]>=nums[i+1]&&i>=0){ --i; } if(i>=0){ //说明nums不是最大的那个数,则找比nums[i]大的最后一个数 j = i+1; while(nums[j]>nums[i]&&j<nums.size()) ++j; --j; //回溯一个,则j为第一个比nums[i]大数 swap(nums[i],nums[j]); } reverse(nums,i+1); } void swap(int &a, int &b){ a = a ^ b; b = a ^ b; a = a ^ b; } void reverse(vector<int>& nums,int sta){//sta为翻转的起点 int l = sta; int r = nums.size()-1; while(l<r){ swap(nums[l],nums[r]); ++l,--r; } }};
这里的reverse是自己写的,当然也可以调用系统函数,使用双向迭代器的reverse
reverse(nums.begin()+i+1,nums.end());
- LeetCode: Next Permutation
- LeetCode Next Permutation
- LeetCode : Next Permutation
- [Leetcode] Next Permutation
- [LeetCode] Next Permutation
- [Leetcode] Next Permutation
- leetcode 88: Next Permutation
- [LeetCode]Next Permutation
- LeetCode-Next Permutation
- [leetcode]Next Permutation
- LeetCode - Next Permutation
- LeetCode 31: Next Permutation
- 【leetcode】Next Permutation
- LeetCode题解:Next Permutation
- 【LeetCode】Next Permutation
- [LeetCode] Next Permutation
- LeetCode Next Permutation
- leetCode | Next Permutation
- hdu 3573 贪心 + 模拟
- 搜索引擎技术原理
- 《世界历史》—史前时期的分期
- 网站制作实战积累-内DIV的margin溢出问题
- hdu 1054 Strategic Game 匈牙利算法 || Hopcroft-Carp算法
- [LeetCode]Next Permutation(!!!)
- POJ-1595
- hdu 1032 The 3n + 1 problem
- function, new function, new Function之间的区别
- SQL语句oracle中如何插入Date类型的数据
- 有向图tarjan 求桥 + 求SCC以及里面的点和它的入度 +缩点 模板 【总结】
- 搜索引擎技术
- BreezeJs用户手册
- 数字信号处理的基础-卷积的理解