找出较大的下一个数字组合 Next Permutation
来源:互联网 发布:python 字典 key 变量 编辑:程序博客网 时间:2024/05/16 00:32
问题: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
思路:先想测试用例,完善的输入用例要比代码重要。
特殊输入用例:
1、末尾是升序:523,只要交换最后两个数即可。
2、整体都是降序:321,需要对整个序列彻底逆置。
3、前面有升序,末尾是降序:13542,记住最后一个极大值点的左侧数(本例是3),
对末尾的降序从右向左找到第一个大于3的数(本例是4),
交换3/4,然后把原来降序的末尾排成升序。
针对上面提到的三种情况,需要做出对应的操作。
class Solution {public: void nextPermutation(vector<int> &num) { int n = num.size(); if(n <= 1) return; int mark = -1; for(int i=0;i<n-1;i++) { if(num[i] < num[i+1]) mark = i;//记住最后的升序(最后一个极大值点的左边) }if(mark == -1) //整体是降序:逆转排成最小的数字{ int left = 0; int right = n-1; while(left < right) swap(num[left++], num[right--]); } else if(mark == n-2) //末尾是升序,交换最后即可 { swap(num[mark], num[mark+1]); return; } else //末尾不是升序,从右向左找出第一个大于num[mark]的数与其交换,其他的数排成升序 { int right = n-1; while(num[right] <= num[mark]) right--; swap(num[mark], num[right]); int left = mark+1; right = n-1; while(left < right) swap(num[left++], num[right--]); } }};
0 0
- 找出较大的下一个数字组合 Next Permutation
- 【leetcode】31. Next Permutation 数字序列的所有组合中比给定串大的下一个最小的串
- 下一个排列(Next Permutation)
- Next Permutation 下一个排列
- Next Permutation 下一个排列
- leetcode-31 Next Permutation 数字排列组合找到下一个更大值
- 31.Next Permutation 下一个排列
- Next Permutation-leetcode下一个排列组合
- 496. Next Greater Element I(寻找下一个较大的数)
- Next Permutation 求下一个排序@LeetCode
- LeetCode Next Permutation 生成下一个序列
- 下一个字典序列(next permutation)
- Next Permutation -- LeetCode(下一个字典序)
- LeetCode | Next Permutation(下一个排列)
- Next Permutation 寻找下一个排列数
- LeetCode 31 Next Permutation(下一个排列)
- [LeetCode]Next Permutation下一个排列问题
- LeetCode 31. Next Permutation(下一个排列)
- mac 安装 nginx 环境
- 基于内容的视频信息检索系统
- IOS-访问HTTP和HTTPS
- 指针与数组&&指针与函数
- [简要笔记]数学之美
- 找出较大的下一个数字组合 Next Permutation
- 字符串匹配经典算法
- 100天坚持行动---相约4月19号
- sudo
- 存储properties资源文件
- rj45接口定义/rj45针脚定义/rj45引脚定义
- 【IOS学习】之九、Blocks的实现续
- Properties资源文件工具类
- 自定义Annotation