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)从最右边向左边遍历,找到第一个左边的数小于右边的数的位置fir;
2)如果fir==0,则说明原来数据是从大到小排序的,此时将整个数组翻转即可;
3)否则,先--fir,令fir指向第一个需要被交换的数,然后从右向左遍历找到第一个比fir的值大的数的位置sec,交换fir和sec的值,将fir后面的数据从小到大排序。
代码实现:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int fir = nums.size() -1, sec = nums.size() -1;
//先找到第一个比前面比后面大的数的位置。如[4,2, 0, 2, 3, 2, 0]里面2,3值2<3
while(fir > 0 && nums[fir] <= nums[fir - 1]) --fir;
//如果是最大数,即题目中的If such arrangement is not possible, it must rearrange it as the lowest possible order成立
if(fir == 0)
{
reverse(nums.begin(), nums.end());
return;
}
--fir; //令fir指向第一个要被交换的元素
while(sec > fir && nums[sec] <= nums[fir]) --sec;
swap(nums[fir], nums[sec]);
//将新交换位置后面的所有数字从小到大排序
sort(nums.begin()+fir+1, nums.end());
}
};