medium程度题
题目:
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
求按字典顺序的下一个排列,方法如下,
1.从右到左找到第一个不符合升序排列的数字m
2.从右到左,找到第一个比m大的数字n
3.交换m和n的位置
4.将m后面一个位置到数组尾的所有元素逆序
AC解
class Solution {
public:
void nextPermutation(vector<int>& nums)
{
int size = nums.size();
if (size <= 1)
return ;
int max_index = INT_MAX;
int len = size - 1;
//找到m的位置
while (len > 0)
if (nums[len] > nums[len - 1])
{
max_index = len - 1;
break;
}
else len--;
//如果找不到,则整个序列是递减的,逆序所有元素
if (len == 0)
{
reverse(nums,0,size - 1);
return ;
}
//找到n的位置
int greater = size - 1;
while(nums[greater--] <= nums[max_index]);
greater++;
//交换m,n 逆序
swap(nums[max_index],nums[greater]);
reverse(nums,max_index + 1,size - 1);
}
void reverse(vector<int> &vec,int i,int j)
{
while (i < j)
{
swap(vec[i],vec[j]);
i++;
j--;
}
}
};