Tuesday, April 12, 2016

[LeetCode] 31. Next Permutation



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
Subscribe to see which companies asked this question

public class Solution {
    
    public void swap(int[] nums, int i, int j){
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
    public void reverse(int[] nums, int s, int e){
        e--;
        while(s < e){
            swap(nums, s, e);
            s++;
            e--;
        }
    }
    
    public boolean nextPermutationAux(int[] nums, int index){
        
        int len = nums.length;
        
        if(index == len-1)
            return false;
        
        if( nextPermutationAux(nums, index+1) ){
            return true;
        }else{
            
            if(nums[index] >= nums[index + 1]){
                // no permutation for current index as well
                return false;
            }else{
                // find the swapping index
                int si = index + 1;
                while(si < len && nums[si] > nums[index]){
                    si++;
                }
                si--;
                
                swap(nums, si, index);
                
                // reverse array
                reverse(nums, index+1, len);
                return true;
                
            }
            
        }
        
    }
    
    public void nextPermutation(int[] nums) {
        
        if( false == nextPermutationAux(nums, 0) ){
            reverse(nums, 0, nums.length);
        }
        
        return;
    }
}

No comments:

Post a Comment