Next Permutation

Problem:

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

Leetcode link
Lintcode link

Solution:




Image from http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*************************************************************************
> File Name: NextPermutation.java
> Author: Yao Zhang
> Mail: psyyz10@163.com
> Created Time: Thu 12 Nov 12:53:41 2015
************************************************************************/


public class NextPermutation{
public void nextPermutation(int[] nums) {
int partitionIndex = -1;
for (int i = nums.length - 2; i >= 0; i--){
if (nums[i] < nums[i + 1]) {
partitionIndex = i;
break;
}
}

if (partitionIndex != -1){
int changeIndex = 0;
for (int i = nums.length - 1; i >= 0; i--){
if (nums[partitionIndex] < nums[i]){
changeIndex = i;
break;
}
}
swap(nums,partitionIndex,changeIndex);
}

int start = partitionIndex + 1;
int end = nums.length - 1;

reverse(nums, start, end);
}

public void reverse(int[] array, int start, int end){
for (int i = start, j = end; i < j; i++, j--)
swap(array, i, j);
}

public void swap(int[] array, int index1, int index2){
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
}

Related Problems: