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
Solution:
class Solution {
public void nextPermutation(int[] nums) {
if(nums==null) return;
int i=nums.length-2;
while(i>=0&&nums[i+1]<=nums[i]){
i--;
}
if(i>=0){
int j=nums.length-1;
while(j>i&&nums[j]<=nums[i]){
j--;
}
swap(i,j,nums);
}
reverse(i+1,nums);
}
private void reverse(int i,int[] a){
int l=i,r=a.length-1;
while(l<r){
swap(l,r,a);
l++;r--;
}
}
private void swap(int i,int j,int[] a){
int tmp=a[j];
a[j]=a[i];
a[i]=tmp;
}
}
时间O(n)
空间O(1)
更像是规律题,不过我题都没读懂,大意是找下一个排列,如果数组降序则说明是最后一种排列,下一种就是最初的状态(升序)。言外之意是每个排列,从右边遍历到左边,数字应该是依次升序,找到不是升的那个数字,和右边第一个高于它的数字交换,然后反转它的位置(注意这个它,是不是升的那个数字xD)后一个开始的数组。
网友评论