【LeetCode】 31. Next Permutation
来源:互联网 发布:淘宝品质退款率怎么降 编辑:程序博客网 时间:2024/06/05 19:22
【LeetCode】 31. Next Permutation
介绍
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,23,2,1 → 1,2,31,1,5 → 1,5,1
题意:
实现“下一个排列”函数,将排列中的数字重新排列成字典序中的下一个更大的排列。如果这样的重新排列是不可能的,它必须重新排列为可能的最低顺序(即升序排序)。重排必须在原地,不分配额外的内存。
解答
考虑序列4,3,2,1
,显然对于此序列中并不存在比其更大的,因为此序列中是降序排列的,是此数字全排列的最大值。
考虑6 2 4 8 7 5 1
,其下一个序列应该是6 2 5 1 4 7 8
。
其步骤应该如下:
1. n>0且n
class Solution {public: void nextPermutation(vector<int>& nums) { int n = nums.size()-1; int left,right; //步骤1:寻找 nums[n-1] >= nums[n] while(n > 0 && nums[n-1] >= nums[n]) --n; if(n>0) { int index = n-1; //步骤2:n-1是大于nums[index]的最小值 while(n < nums.size() && nums[index] < nums[n]) ++n; //步骤3:交换 swap(nums[index],nums[n-1]); left = index+1; }else left = 0; right = nums.size()-1; while(left < right) swap(nums[left++],nums[right--]); return; }};
阅读全文
0 0
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- Leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- [LeetCode]31. Next Permutation
- [LeetCode]31. Next Permutation
- LeetCode 31. Next Permutation
- 【leetcode】31. Next Permutation
- LeetCode *** 31. Next Permutation
- leetcode 31. Next Permutation
- Vue豆瓣系列文章
- 题目1004:Median 2011年浙江大学计算机及软件工程研究生机试真题
- iOS之webview进度条控件NJKWebViewProgress的使用
- 设置NPM淘宝代理镜像
- 当 better-scroll 遇见 Vue
- 【LeetCode】 31. Next Permutation
- Android 怎么退出整个应用程序?
- Vue-book 2.0 一个移动端简单的全栈 web APP
- 构造(Virtual Participation,HDU 5334)
- windows平台如何装win7系统
- Vue全家桶+Mint-Ui打造高仿QQMusic,搭配详细说明
- Json,String,Map之间的转换
- Vue2.0全家桶仿腾讯体育APP
- jQuery UI 工作原理