[LintCode] Previous Permutation

2016-08-03 onkytipsfc

Problem

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]

Note

Solution

public class Solution {
    public ArrayList<Integer> previousPermuation(ArrayList<Integer> nums) {
        int pre = nums.size()-1;
        while (pre > 0 && nums.get(pre-1) <= nums.get(pre)) pre--;
        pre--;
        if (pre >= 0) {
            int cur = pre+1;
            while (cur < nums.size() && nums.get(cur) < nums.get(pre)) cur++;
            cur--;
            int temp = nums.get(cur);
            nums.set(cur, nums.get(pre));
            nums.set(pre, temp);
        }
        int left = pre+1;
        int right = nums.size()-1;
        while (left < right) {
            int temp = nums.get(left);
            nums.set(left, nums.get(right));
            nums.set(right, temp);
            left++;
            right--;
        }
        return nums;
    }
}

内容来源:https://segmentfault.com/a/1190000005352696


用户评论
开源开发学习小组列表