Monday, March 2, 2015

31. Next Permutation Leetcode Java

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
Solution:
This problem is kind of find the relation between the given permutation with the next permutation.
Eg. 2,4,7,6,5,3,1
The pattern is 
1. Find the first num from right to left that is not in ascending order, which is 4 in my example record the position start=1
2. Then find the next number which is bigger than 4, which is 5
3. swap those two numbers-> 2,5,7,6,4,3,1
4 reverse the part of the array from(start(1) to end) -> 2,5,1,3,4,6,7
The start is initiated with 0, so if in the first step, we can't find the right number, it will reverse the whole array just like the problem required 3,2,1-> 1,2,3
Time Complexity(O(n))
 public void nextPermutation(int[] num) {  
    if(num==null || num.length<2) return;  
    int start=0;  
    for(int i=num.length-1;i>=0;i--){  
      if(i>0 && num[i]>num[i-1]){  
        start=i;  
        int j=i;  
        while(j<num.length && num[j]>num[i-1]) j++;  
        int temp=num[i-1];  
        num[i-1]=num[j-1];  
        num[j-1]=temp;  
        break;  
      }  
    }  
    reverse(num,start);  
   }  
   public void reverse(int[] num, int start){  
     int end=num.length-1;  
     while(start<end){  
       int temp=num[start];  
       num[start]=num[end];  
       num[end]=temp;  
       start++;  
       end--;  
     }  
   }  

No comments:

Post a Comment