Skip to content

Instantly share code, notes, and snippets.

@AkshayMathur92
Forked from guolinaileen/Next Permutation.java
Created August 26, 2016 10:21
Show Gist options
  • Save AkshayMathur92/64e98993f17ccf269a7da56f9f04abce to your computer and use it in GitHub Desktop.
Save AkshayMathur92/64e98993f17ccf269a7da56f9f04abce 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