Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Last active December 15, 2020 15:01
Show Gist options
  • Save guolinaileen/4672038 to your computer and use it in GitHub Desktop.
Save guolinaileen/4672038 to your computer and use it in GitHub Desktop.
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…
public class Solution {
public void nextPermutation(int[] num) {
if(num.length==0) return;
int length=num.length;
int end=length-1;
int i=end-1;
for(; i>=0; i--)
{
if(num[i]>=num[i+1]) continue; //get an increasing set from the end
int j=end;
while(j!=i)
{
if(num[j]>num[i])
{
int temp=num[i];
num[i]=num[j];
num[j]=temp;
break;
}
j--;
}
break;
}
reverse(num, i+1, end);
return;
}
void reverse(int []num, int start, int end)
{
while(start<end)
{
int temp;
temp=num[start];
num[start]=num[end];
num[end]=temp;
start++;
end--;
}
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment