2014年4月11日 星期五

[LeetCode] Next Permutation

Problem:
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:O(n^2)
public class Solution {
    public void nextPermutation(int[] num) {
        if(num == null || num.length <=1)
            return;
        
        int left = -1; 
        int right = num.length;
        
        for(int i = num.length-1; i>0; i--){
            for(int j = i-1; j> left&& j>=0;j--){
             if(num[i] > num[j]){
               left = j;
               right = i;
               break;
             }
            }
        }
        if(left >=0){
         int tmp = num[left];
         num[left] = num[right];
         num[right] = tmp;
         left++;
        }else{
         left = 0;
        }
        Arrays.sort(num,left,num.length);
    }
}
Key Concept: find the right most going up point and sort all element from that point.

沒有留言:

張貼留言