原题
https://leetcode.com/problems/next-permutation/
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
思路
指针i从后往前找到第一个前面比后面小的数nums[i-1],此时i:end均为从大到小排序。
指针j从后往前找到第一个比nums[i-1]大的数nums[j]。此时nums[j]为i:end中的最小数。
交换nums[i-1]与nums[j],此时i:end依然为从大到小排序。
将i:end倒序,此时变成从小到大排序。完成。
代码
1 | class Solution: |