【Leetcode 31】Next Permutation
难度: 中等(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
分析:如果数组从大到小有序,则当前为最大,只需转为从小到大排序即可。如果不是,那么此时需从右至左扫描找到第一个num[i]>nums[i-1]的下标,在i-1右边选出比nums[i-1]大的最小的数交换,然后从小到大将i-1之后的数字排序即可。
代码:
1 | def pop_sort(self,nums,l,r): |
评论系统未开启,无法评论!