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 and use only constant 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
思考:排列问题。当排列的序列为递减序列时,则其下一个排列序列为递增序列,即反转序列。这里其实给了我们一个提示。
算法步骤:
1.从后往前找到第一个非递增的数字,记录下标为i
2.从后往前找到第一个大于nums[i]的数字,记录下标为j
3.交换nums[i]和nums[j]两个数字的位置
4.从i+1位置开始,反转后面的序列
实现代码如下:
class Solution {
public void nextPermutation(int[] nums) {
int i = nums.length - 2;
//找到第一个非递增的数字(从后往前)
while(i>=0 && nums[i+1] <= nums[i]){
i--;
}
if(i >= 0){
int j = nums.length - 1;
//从后往前找,找到第一个大于nums[i]的数字
while(j >= 0 && nums[j] <= nums[i]){
j--;
}
//交换
swap(nums,i,j);
}
reverse(nums,i + 1);
}
private void reverse(int[] nums,int start){
int i = start,j = nums.length - 1;
while(i<j) {
swap(nums,i,j);
i++;
j--;
}
}
private void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}