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
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从后往前,在i后面找比i位大的最小值,交换i和找到那个位置的值,然后在i后面的排个序!
class Solution {
public:
void nextPermutation(vector<int>& nums)
{
if (nums.size() < 2)
return;
int swap_pos;
int swap_value;
for (int i = nums.size() - 2; i >= 0; i--)
{
swap_value = INT_MAX;
for (int j = i + 1; j <= nums.size() - 1 ; j++)
{
if (nums[i] < nums[j] && nums[j] < swap_value)
{
swap_value = nums[j];
swap_pos = j;
}
}
if (swap_value != INT_MAX)
{
swap(nums[i], nums[swap_pos]);
sort(nums.begin() + i + 1, nums.end());
return;
}
}
sort(nums.begin(), nums.end());
return;
}
};