标签:must public ble size ssi http number space 数字
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 and use only constant 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
code
一个数组的升序排序后的顺序是所有排列中最小的一个序列,要找到他的下一个较大的序列要从数组最后找到第一个非逆序的数字。
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: void nextPermutation(vector<int>& nums) { if(nums.size()<2) return ; auto cur=nums.end()-1; auto pre=cur-1; while(pre>=nums.begin()&&*pre>=*cur) { --cur; --pre; } if(pre<nums.begin()) { reverse(nums.begin(),nums.end()); return; } for(cur=nums.end()-1;cur>pre&&*cur<=*pre;--cur); swap(*cur,*pre); reverse(pre+1,nums.end()); return ; } }; int main() { vector<int> arr{1,5,1}; //2 1 3 Solution s; s.nextPermutation(arr); for(auto i:arr) cout<<i<<" "; return 0; }
标签:must public ble size ssi http number space 数字
原文地址:https://www.cnblogs.com/tianzeng/p/10828095.html