Next Permutation
来源:互联网 发布:淘宝麻辣烫底料 编辑:程序博客网 时间:2024/05/29 15:13
ARRAY;
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
首先找到:: 需要交换的元素i,j。然后交换。 之后进行reverse。
其中::1,2,3.最后一个升序的,2,3将其交换就好
如 其他的,抓住最后一个升序的,
最后一个升序的小技巧,找到比后面小的数,然后找到最后一个大的数字。
class Solution {public: void reversePart(vector<int>& nums,int k){int j=nums.size()-1; int i=k+1;while(i<=j){swap(nums[i],nums[j]); i++; j--;}}void nextPermutation(vector<int>& nums){int flag=0;if(nums.size()==1)return;//find jint i=nums.size()-1;while (i>0&&nums[i-1]>=nums[i])//after is bigger.{i--;}int j=i;//difficult for me.while(j<nums.size()&&nums[j]>nums[i-1])j++;if(i==0)reversePart(nums,-1);else{swap(nums[i-1],nums[j-1]);reversePart(nums,i-1);}}};
如有不对的地方,请指正!
0 0
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Apache Maven 使用 profile 和 filtering 实现多种环境下的资源配置管理
- hdoj1342 Lotto
- 备份
- iOS开发所有KeyboardType与图片对应展示
- LeetCode(201) Bitwise AND of Numbers Range
- Next Permutation
- 关于HttpClient在服务器端使用请求碰到的问题总结
- ]Erlang进程堆垃圾回收机制
- 莱特币LTC矿池p2pool架设之Linux篇(自动调节矿工难度)
- iOS多线程编程之GCD
- LeetCode题解:Contains Duplicate II
- 备份
- CocoaPods安装和使用教程
- CoreData之条件查询 contains