问题描述
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,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
问题描述:
找出当前排列的下一个值。可以将当前数组认为是一个字符串,比较的时候是依次比较大小,得到只比他大一个的数。
解决方法:
比当前数组值只大一个的是:从最后一位开始找到第一个不是不是递增的数值,然后从递增的支付串中找出第一个比当前值大交换位置。然后将后面的位置中的所有的值进行升序排序就好。
例如: 2137540.下一个值应该是 首先找到 3,然后从3后面的值当中找到第一个比他大的值4,交换位置得到 2147530.然后把4后面的数进行升序排序得到 2140357。
代码实现:
public void nextPermutation(int[] nums) {
int index = nums.length - 2;
while (index >= 0 && nums[index] >= nums[index + 1]) {
index--;
}
if (index < 0) {
reverse(nums, 0, nums.length - 1);
} else {
//从index+1 开始找出第一个 大于当前indx值的数
int lastIndex = nums.length - 1;
while (nums[lastIndex] <= nums[index] && lastIndex > index) {
lastIndex--;
}
int temp = nums[index];
nums[index] = nums[lastIndex];
nums[lastIndex] = temp;
reverse(nums, index + 1, nums.length - 1);
}
}
/**
* 交换两个数
*
* @param nums
* @param left
* @param right
*/
private void swap(int nums[], int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
/**
* 将两个数进行变化
*
* @param nums
* @param left
* @param right
*/
protected void reverse(int nums[], int left, int right) {
while (right > left) {
swap(nums, left, right);
left++;
right--;
}
}
遇到的问题:
在做的过程中遇到的问题是:
确定第一个值的位置,nums[index] >= nums[index + 1]。容易忽略这个 = 。等于也需要过滤掉。
然后是后期的排序,由于这个值是升序的,所以可以用一个交换,从而将复杂度降到O(N).