lintcode-medium-Previous Permutation

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Previous Permutation相关的知识,希望对你有一定的参考价值。

Given a list of integers, which denote a permutation.

Find the previous permutation in ascending order.

 

 Notice

The list may contains duplicate integers.

Example

For [1,3,2,3], the previous permutation is [1,2,3,3]

For [1,2,3,4], the previous permutation is [4,3,2,1]

 

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A list of integers that‘s previous permuation
     */
    public ArrayList<Integer> previousPermuation(ArrayList<Integer> nums) {
        // write your code

        if(nums == null || nums.size() == 0)
            return nums;
           
        int i = nums.size() - 2;
        for(; i >= 0; i--){
            if(nums.get(i) > nums.get(i + 1))
                break;
        }
        
        if(i == -1){
            reverse(nums, 0, nums.size() - 1);
            return nums;
        }
        
        int j = i + 1;
        for(int k = j; k < nums.size(); k++){
            if(nums.get(k) < nums.get(i) && nums.get(k) >= nums.get(j))
                j = k;
        }
        
        swap(nums, i, j);
        reverse(nums, i + 1, nums.size() - 1);
        
        return nums;
    }
    
    public void swap(ArrayList<Integer> nums, int i, int j){
        int temp = nums.get(i);
        nums.set(i, nums.get(j));
        nums.set(j, temp);
        
        return;
    }
    
    public void reverse(ArrayList<Integer> nums, int i, int j){
        while(i < j){
            swap(nums, i, j);
            i++;
            j--;
        }
        
        return;
    }
    
}

 

以上是关于lintcode-medium-Previous Permutation的主要内容,如果未能解决你的问题,请参考以下文章