Java [leetcode 31]Next Permutation

题目描述:

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

解题思路:

从整个数组的最后开始往前判断,直到找到相邻两个数是增加的,记录下这个位置为i;

如果i小于0,表示整个数组的顺序是递减的;

从数组的最后开始寻找,找到第一个大于nums[i]的数的位置,记为j;

交换nums[i]和nums[j]的位置,然后对i后的所有数组进行倒序排列。

注意边界问题,数组不要越界。

代码如下:

public class Solution {
    public void nextPermutation(int[] nums) {
		if (nums.length < 2)
			return;
		int i, j, temp;
		for (i = nums.length - 2; i >= 0; i--) {
			if (nums[i] < nums[i + 1])
				break;
		}
		for (j = nums.length - 1; j >= 0; j--) {
			if (i < 0)
				break;
			if (nums[j] > nums[i])
				break;
		}
		if (i >= 0) {
			temp = nums[i];
			nums[i] = nums[j];
			nums[j] = temp;
		}

		if (i < nums.length - 2) {
			for (int k = i + 1; k <= (nums.length - i - 2) / 2 + i + 1; k++) {
				temp = nums[k];
				nums[k] = nums[nums.length + i - k];
				nums[nums.length + i - k] = temp;
			}
		}
	}
}
原文地址:https://www.cnblogs.com/zihaowang/p/4930287.html