#190 Next Permutation II

来源:互联网 发布:阿里巴巴云计算张北 编辑:程序博客网 时间:2024/06/17 01:34

题目描述:

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).

Example

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

Challenge 

The replacement must be in-place, do not allocate extra memory.

题目思路:

这题怎么说呢,就是重在观察。从数组的后面往前看:如果nums[i] < nums[i - 1],这是没问题的;一旦nums[i] > nums[i - 1],这个应有的顺序就乱了,那么从nums[i - 1]开始,我们就可以从新排序得到next permutation。

举个例子来说:[1,1,5,4,2,7,6,4,3]

后面的7,6,4,3都没有问题,问题在2,7这里。找到2所在的index之后,可以发现next permutation应该是1,1,5,4,3,xxxx。这个3是怎么来的呢?这个3是在2,7,6,4,3这些数中大于2的最小数。所以算法中就是要寻找index - 1的坐标之后大于nums[index - 1]的最小数,用来替换index - 1的位置。

搞定这些之后就好办了,把剩下的数从小到大排序一下就是答案了。

Mycode(AC = 14ms):

class Solution {public:    /**     * @param nums: a vector of integers     * @return: return nothing (void), do not return anything, modify nums in-place instead     */    void nextPermutation(vector<int> &nums) {        // write your code here        if (nums.size() <= 1) return;                // find the index of number where nums[index] > nums[index - 1]        int index = -1;        for (int i = nums.size() - 1; i > 0; i--) {            if (nums[i] > nums[i - 1]) {                index = i;                break;            }        }                // if index not found, then it is already largest number        if (index == -1) {            reverse(nums.begin(), nums.end());        }        else {            // find the min number which is larger than nums[index - 1],            // in the index ~ end            int second_min = nums[index], smin_idx = index;            for (int i = index + 1; i < nums.size(); i++) {                if (nums[i] > nums[index - 1] && nums[i] < second_min) {                    second_min = nums[i];                    smin_idx = i;                }            }                        // swap the min number with nums[index - 1]            int tmp = nums[index - 1];            nums[index - 1] = nums[smin_idx];            nums[smin_idx] = tmp;                        // sort numbers after index - 1            sort(nums.begin() + index, nums.end());        }    }};


0 0
原创粉丝点击