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
public void NextPermutation(int[] nums)
{
int i = nums.Length - 2;
//末尾向前查找,找到第一個i,使得A[i] < A[i+1]
while (i >= 0 && nums[i + 1] <= nums[i])
{
i--;
}
if (i >= 0)
{
//從i下标向後找第一個j,使得A[i]<A[j]
int j = nums.Length - 1;
while (j >= 0 && nums[j] <= nums[i])
{
j--;
}
//交換i,j
Swap(nums, i, j);
}
//逆置j之後的元素
Reverse(nums, i + 1, nums.Length);
}
//逆置排序
private void Reverse(int[] nums, int start, int end)
{
int i = start, j = end - 1;
while (i < j)
{
Swap(nums, i, j);
i++;
j--;
}
}
//交換
private void Swap(int[] nums, int i, int j)
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}