每日一题 2019 - 03 - 14
题目:
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 | `1,2,3` → `1,3,2` |
解法:
这个题让我们找出当前序列中的下一个全排列序列,如果当前全排列序列为最大的顺序,则将其转换为初始序列。
思路大概如下,设给定数字串为A[N]
,令 i = n - 1
- 从数字串后面往前走,找到
A[i] > A[i-1]
的位置i
,那么证明从n-1
到i
为递减的序列 - 从
i
到N - 1
中找出一个比A[i-1]
大的数字A[temp]
,然后交换A[i-1]
与A[temp]
- 由于此时后
N-i+1
位已经进入了下一个全排列的状态,将后N-i+1
位翻转,即得到下一个全排列序列 - 如果给定序列本身就是降序,那么直接翻转
代码:
1 | class Solution { |