leetcode编程记录16 #31 Next Permutation

来源:互联网 发布:数据库安全性设计 编辑:程序博客网 时间:2024/06/08 14:13

leetcode编程记录16 #31 Next Permutation

标签(空格分隔): leetcode


这次的题目是稍微有点难度的题目,是要我们对数字进行重排列的一道题目,题目如下:

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

题目分析与理解:要想做出这道题目,关键是要能够明白数字按字典序进行排列是什么样的操作,然后再寻找下一个排列。由题目可以知道所谓的数字的下一个排列实际上是尽量不要改变前面数字的排列顺序,而是先来改变后面数字的顺序的一种排列方式,比如说1,2,3是一个最小的排列因为这是一个升序的排列,它的下一个排列就是1,3,2。为什么不是其它的顺序呢?因为按照字典顺序的习惯,总是将前面部分相同的排在一起,后面逐渐变大的排在较后的位置,所以当我们在后面的数字部分无法再一次进行较大的排序的时候,我们就要重排,后面按照降序排列的数字的部分,使之变为升序的排列,然后我们再把这些数的前一个数与这些数中最小的比这个数大的数进行交换,完成一次重排。

代码如下:

class Solution {public:    void nextPermutation(vector<int>& nums) {        int len = nums.size();        if (len <= 1) {return;}        int flag = 0;        for (int i = len - 1; i > 0; --i)        {            if (nums[i] > nums[i - 1]) {                reverseArray(nums, i, len - 1);                int bigI = i;                for (int j = i; j < len - 1; j++) {                    if (nums[j] <= nums[i - 1] && nums[i - 1] < nums[j + 1]) {                        bigI = j + 1;                        break;                    }                }                swap(nums[bigI], nums[i - 1]);                return;            }        }        reverseArray(nums, 0, len - 1);    }    void swap(int & a, int & b) {        int temp = a;        a = b;        b = temp;    }    void reverseArray(vector<int>& nums, int left, int right) {        for (int i = left, j = right; i < j; ++i, --j)        {            swap(nums[i], nums[j]);        }    }};
原创粉丝点击