Next Permutation

来源:互联网 发布:种植牙费用 知乎 编辑:程序博客网 时间:2024/06/10 20:02

题目:

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,31,3,2
3,2,11,2,3
1,1,51,5,1


思想:

由题意可知,我们需要讨论两种情况,

第一种情况是,所组成的数已经是最大的数,我们需要输出一个最小的数。

第二种情况是,仍存在一个较大的数。

从后向前遍历数组,若发现,所有数均是逆序排序的,则对其排序,输出结果。否则,逆序遍历数组,找到第一个满足小于当前元素的数,并将二者置换,注意,此时由于发生元素的交换,为保证该数大于原数的最小数,需将置换位后的数据进行顺序排序。


代码:

class Solution {public:void nextPermutation(vector<int>& nums) {int length = nums.size();int k = -1;for ( int i = length-2; i >= 0; i--){if (nums[i]>=nums[i + 1])continue;elsek = i;break;}if (k == -1)//处理已是最大数的情况{ sort(nums.begin(),nums.end());}else{int index = -1;for (int  i = length-1; i > k; i--){if (nums[i] > nums[k]){index = i;break;}}swap(nums[k], nums[index]);sort(nums.begin()+k + 1, nums.end());}}};

0 0