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.

Have you met this question in a real interview? Yes
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]

分析

请参阅 Next Permutation(下一个排列)。

代码

public class Solution {
    /*
     * @param nums: A list of integers
     * @return: A list of integers that's previous permuation
     */
    public List previousPermuation(List nums) {
        // write your code here
        int index=-1;
        for (int i = nums.size() - 2; i >= 0; i--) {
            if (nums.get(i+1) < nums.get(i)) {
                index=i;
                for (int j = nums.size() - 1; j > i; j--) {
                    if (nums.get(j)< nums.get(i)) {
                        int temp = nums.get(i);
                        nums.set(i,nums.get(j));
                        nums.set(j,temp);
                        break;
                    }
                }
                break;
            }
        }
        reverse(nums,index+1, nums.size() - 1);
        return nums;
    }
    private void reverse(List nums, int start, int end) {
        for (int i = start, j = end; i < j; i++, j--) {
                int temp = nums.get(i);
                nums.set(i,nums.get(j));
                nums.set(j,temp);
        }
    }
}

你可能感兴趣的:(Previous Permutation(上一个排列))