Monday, February 3, 2014

Next Permutation (Java)

LeetCode

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-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


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-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
Time complexity n+n+logn-> O(n);
public class Solution {
public void nextPermutation(int[] num) {
for (int i=num.length-1; i>0; i--){
if (num[i]>num[i-1]){
reverse(num, i, num.length-1);
// can use normal back to front scan replace bsearch, not slow so much, but bsearch is better
int j=bSearch(num, num[i-1]+0.5, i,num.length-1);
int temp=num[j];
num[j]=num[i-1];
num[i-1]=temp;
return;
}
}
Arrays.sort(num);
}
private int bSearch(int[] num, double target,int start, int end ){
while (start<=end){
int mid=(start+end)/2;
if (num[mid]==target)
{
return mid;
}
else if (num[mid]>target){
end=mid-1;
}
else{
start=mid+1;
}
}
return start;
}
private void reverse(int[] num, int start, int end){
while (start<end){
int temp=num[start];
num[start]=num[end];
num[end]=temp;
start++;
end--;
}
}
}

No comments:

Post a Comment