48_leetcode_Next Permutation
来源:互联网 发布:js继承题目 编辑:程序博客网 时间:2024/05/07 17:38
mplement 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:特殊情况, size <= 1;2:从后到前遍历数组, 比较当前数字大小与前一个数字的大小,如果当前数字小,则向前移动;3:如果不存在后一个数字大于前一个数字,则直接排序数组,并返回;4:找到相应的索引,替换数字,并对数组后面的部分进行排序。
void nextPermutation(vector<int>& num) { if(num.size() <= 1) { return; } int curIndex = (int)num.size() - 1; for(; curIndex >= 1; curIndex--) { if(num[curIndex] > num[curIndex - 1]) break; } //从后到后非降序排列 if(curIndex == 0) { sort(num.begin(), num.end()); return; } int lastIndex = curIndex - 1; int minIndex = curIndex; int minNumber = num[curIndex]; for(int i = curIndex + 1; i < (int)num.size(); i++) { if(num[i] > num[lastIndex] && num[i] < minNumber) { minNumber = num[i]; minIndex = i; } } swap(num[lastIndex], num[minIndex]); sort(num.begin() + lastIndex + 1, num.end()); return; }
0 0
- 48_leetcode_Next Permutation
- Permutation
- Permutation
- permutation
- Permutation
- Permutation
- Permutation
- permutation
- Permutation
- permutation
- Permutation
- Permutation
- permutation
- permutation
- permutation
- Permutation, next Permutation, Permutation sequence
- Complete Permutation
- 排列(Permutation)
- 利用 matlab 读取SAR 元数据
- android 图片解码显示流程
- 黑马程序员--.NET笔记--枚举、数组、排序、方法、变量的作用域、重载
- IllegalStateException: Can not perform this action after onSaveInstanceState解决办法
- web.xml
- 48_leetcode_Next Permutation
- xml的开发及文件表
- boost::format sprintf QString 字符串处理
- TextFx-Ease Function(缓动函数)
- MYSQL字段,表名大小写的问题 CASE IN-SENSITIVE MYSQL ON LINUX
- 账务账号的修改
- daemon 的命名守则
- header('Content-Type:text/xml'); 使用header函数时候的注意事项
- 计算机学习