【LeetCode算法练习(C++)】Next Permutation
来源:互联网 发布:node mysql query参数 编辑:程序博客网 时间:2024/05/16 14:45
题目:
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
链接:Next Permutation
解法:求下一个全排列,从后向前找到第一个顺序对,将后者插入前者之前,并反转中间部分。同时可以使用next_permutation库函数直接解决。时间O(n^2)
class Solution {public: void nextPermutation(vector<int>& nums) { int i, j; for (i = nums.size() - 2; i >= 0; --i) { if (nums[i] < nums[i + 1]) break; } for (j = nums.size() - 1; j >= i ; --j) { if (nums[j] > nums[i]) break; } if (i >= 0) { swap(nums[i], nums[j]); } reverse(nums.begin() + i + 1, nums.end()); return; }};
Runtime: 12 ms
阅读全文
0 0
- 【LeetCode算法练习(C++)】Next Permutation
- [leetcode-31]Next Permutation(C)
- LeetCode算法题目:Next Permutation
- LeetCode(31): Next Permutation (C++)
- Leetcode c语言-Next Permutation
- leetcode:Next Permutation (求下一个排列) 【面试算法题】
- LeetCode OJ算法题(三十):Next Permutation
- 每周LeetCode算法题(三):Next Permutation
- LeetCode(31) Next Permutation
- LeetCode (31)Next Permutation
- LeetCode刷题(C++)——Next Permutation(Medium)
- LeetCode算法题之Next Permutation
- 算法作业HW23:LeetCode 31 Next Permutation
- LeetCode算法题——Next Permutation
- [LeetCode] 031. Next Permutation (Medium) (C++/Python)
- leetcode刷题系列C++-next permutation
- 【C++】【LeetCode】31. Next Permutation && 46. Permutations
- LeetCode 题解(4):Next Permutation
- Android 代码管理工具Git,Repo 工具
- 增强学习之时间差分法(TD方法)
- oracle的imp导入时覆盖目标数据库
- C#向数据库添加数据遇到问题——报错“‘*’附近有语法错误”
- PHP7革新与性能优化
- 【LeetCode算法练习(C++)】Next Permutation
- C++ Primer 知识点总结 (第二章)
- Error:java: Compilation failed: internal java compiler error
- C++程序中启动线程的方法
- Hyperledger Fabric SDK 示例fabric-samples-《balance-transfer》之九《查询指定的交易信息》
- 关于计算机视觉(ComputerVision, CV)相关领域的网站链接
- vue-router菜鸟进阶!(路由组件传参 vs H5 History模式)
- 前端语言学习网址
- 常见的移动端H5页面开发遇到的坑和解决办法