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 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
这个题的意思是找到下一个最大的排列数,方法类似于双指针,从后往前扫,当遇到可以进行更换的数的时候进行更换,并使用reverse进行反转后面的数,使得后面的数为最小的。
1)
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size() <= 1){
return ;
}
int i = nums.size() - 1;
while(i > 0 && nums[i] <= nums[i - 1]){
--i;
}
if(i == 0){
reverse(nums.begin(),nums.end());
}else{
int j = nums.size() - 1;
while(nums[j] <= nums[i - 1]){
--j;
}
swap(nums[j],nums[i - 1]);
reverse(nums.begin() + i , nums.end());
}
}
};
2)
static const auto _______ = [](){//大概是一种特殊的读取数的形式
std::cout.sync_with_stdio(false);
cin.tie(0);
return 0;
}();
class Solution {
public:
void nextPermutation(vector<int>& a) {
int n=a.size();
int i;
for(i=n-1;i>0;i--) {
if(a[i]>a[i-1]) {
int k=i;
for(int j=i;j<n;j++) {
if(a[j]>a[i-1]&&a[j]<a[k])
k=j;
}
swap(a[i-1],a[k]);
break;
}
}
sort(a.begin()+i,a.end());
}
};