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
Idea: This question can be considered as one middle step during the process of evolving the first permutation to the last permutation, e.g. from 1, 2, 3 to 3, 2, 1. The elements in the first permutation are in ascending order, while the last permutation is descending order. So the problem is how to make the sequence from ascending order to descending order with smallest "jump" each time.
There are formal ways to do the evolution:
1) From right to left, find the first number which violates the ascending order, mark it as partitionNumber.
2) From right to left, find the first number which is larger than the partitionNumber, mark it as changeNumber.
3) swap the partitionNumber and the changeNumber.
4) reverse the numbers on the right of partitionNumber.
5) A special case is the permutation is already the last permutation which is already in descending order (from left to right). So the four steps above actually has not affects on the sequence. However, the next permutation of the last permutation is the first permutation. In order words, we just need to reverse the whole sequence.
Time: O(n) Space: O(1)
Code:
public class Solution {
public void nextPermutation(int[] num) {
if(num.length<=1)
return;
int parNum=num.length-2;
while(parNum>=0)
{
if(num[parNum]<num[parNum+1])
{
int chanNum=num.length-1;
while(chanNum>parNum-1)
{
if(num[chanNum]>num[parNum])
break;
chanNum--;
}
swap(num,parNum,chanNum);
reverse(num,parNum+1,num.length-1);
return;
}
parNum--;
}
reverse(num,0,num.length-1);
}
public void swap(int[] num, int i, int j)
{
int tmp=num[i];
num[i]=num[j];
num[j]=tmp;
}
public void reverse(int[] num,int left,int right)
{
for(int i=left,j=right;i<j;i++,j--)
swap(num,i,j);
}
}
No comments:
Post a Comment