一、最近最大换位数

12345的倒数第3位是3，我们需要从后面的逆序区域中寻找到刚刚大于3的数字，和3的位置进行互换：

12453

12435

1. 从后向前查看逆序区域，找到逆序区域的前一位，也就是数字置换的边界
2. 把逆序区域的前一位和逆序区域中刚刚大于它的数字交换位置
3. 把原来的逆序区域转为顺序


private static int findTransferPoint(int[] nums) {
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
return i;
}
}
return 0;
}

private static int[] exchange(int[] nums, int index) {
int head = nums[index - 1];
for (int i = nums.length - 1; i > 0; i--) {
nums[index - 1] = nums[i];
break;
}
}

return nums;
}

private static int[] reverse(int[] nums, int index) {
for (int i = index, j = nums.length - 1; i < j; i++, j--) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
return nums;
}

public static int[] findNearestNum(int[] nums) {

int[] numsCopy = Arrays.copyOf(nums, nums.length);
int index = findTransferPoint(numsCopy);
if (index == 0) {
return null;
}
exchange(numsCopy, index);
reverse(numsCopy, index);
return numsCopy;
}



    public static void main(String[] args) {

int[] nums = {1,2,3,5,4};
System.out.println("before: "+Arrays.toString(nums));

findNearestNum(nums);
System.out.println("result: "+Arrays.toString(findNearestNum(nums)));
}

before: [1, 2, 3, 5, 4]
before: [1, 2, 4, 3, 5]

二、全排列

n个不相同的数字的全排列有n!个，写个函数求n的阶乘：

    private static int factorrail(int n) {
if (n == 1) {
return 1;
} else {
return n * factorrail(n - 1);
}
}

    public static void main(String[] args) {
int[] nums = {5, 1, 2, 3, 4};
Arrays.sort(nums);
int n = factorrail(nums.length);
System.out.println("1:" + Arrays.toString(nums));
for (int i = 2; i <= n; i++) {
nums = findNearestNum(nums);
System.out.println(i + ":" + Arrays.toString(nums));
}
}

1:[1, 2, 3, 4, 5]
2:[1, 2, 3, 5, 4]
3:[1, 2, 4, 3, 5]
4:[1, 2, 4, 5, 3]
5:[1, 2, 5, 3, 4]
6:[1, 2, 5, 4, 3]
...
117:[5, 4, 2, 1, 3]
118:[5, 4, 2, 3, 1]
119:[5, 4, 3, 1, 2]
120:[5, 4, 3, 2, 1]