31. Next Permutation
来源:互联网 发布:安卓和python 编辑:程序博客网 时间:2024/05/09 05:01
题意: 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
分析:找到数组最右侧的两个数nums[a],nums[b],使得nums[a] < nums[b],交换之,并从第a+1个数到数组尾部排序
AC代码:
class Solution {public: void nextPermutation(vector<int>& nums) { int a = 0, b = 0; for(int i = 0; i < nums.size(); ++i){ for(int j = i; j < nums.size(); ++j){ if(nums[j] > nums[i]){ a = i; b = j; } } } if(a == 0 && b == 0){ sort(nums.begin(), nums.end()); return; }else{ int temp = nums[a]; nums[a] = nums[b]; nums[b] = temp; sort(nums.begin() + a + 1, nums.end()); } }};
0 0
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- 31. Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- 31. Next Permutation
- Leetcode 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- 高精度减法
- ubuntu12.04_amd apt-get isntall jdk.jre报错.
- UML图总结
- 信息学奥林匹克竞赛-小鱼的游泳时间
- 初始项目——快速入手之感
- 31. Next Permutation
- MyEclipse new 后面的菜单选项设置
- 高精度除法
- C++ enum
- 单源最短路径之Bellman-Ford 算法
- UML-实现图(构件图和部署图)
- POJ2777线段树(结构体指针实现)
- swift语言主流学习文档
- 栈和队列