Leetcode -- 31. Next Permutation
来源:互联网 发布:java实战项目百度云 编辑:程序博客网 时间:2024/06/05 17:14
题目:
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
思路:这道题还是有点难度的,参考了别人的思路,解法如下:以
以6,8,7,4,3,2
为例:
- 首先从后往前遍历,找到第一个不按递增排列的元素,即
nums[i-1]
,上图中的6。 - 再从后往前,找到第一个比
nums[i-1]
大的元素,即nums[j]
, 上图中的7。 - 交换
nums[i-1]
和nums[j]
的位置,变成7, 8, 6, 4, 3, 2
。 - 对
i → nums.size()-1
的元素进行排序, 变成:7, 2, 3, 4, 6, 8
。
C++代码如下:
void nextPermutation(vector<int>& nums) { if (nums.size() <= 1) return; int right = nums.size() - 1; int i = right,j = right,temp; while (nums[i] <= nums[i - 1]) { --i; } if (i == 0) { sort(nums.begin(), nums.end()); return; } while (nums[i-1] >= nums[j]) { --j; } temp = nums[j]; nums[j] = nums[i-1]; nums[i-1] = temp; sort(nums.begin() + i,nums.end());}
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
- 了解c++中的类型转换
- java 5种设计模式
- How the backpropagation algorithm works
- Linux入门(6)——Ubuntu16.04安装atom
- html
- Leetcode -- 31. Next Permutation
- mysql从服务列表里消失了
- ganglia监控hadoop集群配置
- 我的Linux学习一(CentOS 7在虚拟机中的下载与安装)
- Viterbi译码及matlab代码(一)
- ProxyChains
- ZOJ1047( 深度优先搜索)
- Android启动篇 — init原理(二)
- opencv3绘图操作