Google
31 Next Permutation

1. Question

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,31,3,2 3,2,11,2,3 1,1,51,5,1

2. Implementation

1
class Solution {
2
public void nextPermutation(int[] nums) {
3
int i = nums.length - 1;
4
while (i > 0 && nums[i - 1] >= nums[i]) {
5
--i;
6
}
7
8
if (i > 0) {
9
int j = nums.length - 1;
10
11
while (j >= i && nums[i - 1] >= nums[j]) {
12
--j;
13
}
14
15
swap(nums, i - 1, j);
16
}
17
reverse(nums, i, nums.length - 1);
18
}
19
20
public void swap(int[] nums, int i, int j) {
21
int temp = nums[i];
22
nums[i] = nums[j];
23
nums[j] = temp;
24
}
25
26
public void reverse(int[] nums, int start, int end) {
27
while (start < end) {
28
swap(nums, start , end);
29
++start;
30
--end;
31
}
32
}
33
}
Copied!

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)