题目描述
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. 使用STL中的库函数next_permutation,注意使用方法;
2. 查看《STL源码剖析》后,确认next_permutation的实现方式,手动实现之。即:
(1)从vector的后面找到第一个降序的数字,记录位置为pos;
(2)在vector的后半部分,即[v.begin()+pos+1, v.end()]区间,从后往前查找第一个比v[pos]大的数字,交换两个数的位置;
(3)然后对后半部分重新从小到大排序即可。
注意:如果此种排列为最大(后)一种,则下一种为最小(第一)种排列方式。
实现代码
1.
时间复杂度: O(n) 运行时间: 9ms
class Solution {
public:
void nextPermutation(vector<int>& nums) {
next_permutation(nums.begin(), nums.end());
}
};
2.
使用sort排序时间复杂度: O(nlogn) 运行时间: 9ms
使用reverse时间复杂度: O(n) 运行时间: 9ms
明显后者时间上更优,但运行时间没有差别,想来可能是数据量比较小的原因。
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if (nums.size() == 0) return;
int firstMin = nums[nums.size() -1];
int position = -1;
for (int i = nums.size()-2; i >= 0; --i) {
if (firstMin > nums[i]) {
position = i;
break;
}
else {
firstMin = nums[i];
}
}
if (position != -1) {
for (int i = nums.size()-1; i >= position; --i) {
if (nums[i] > nums[position]) {
int temp = nums[position];
nums[position] = nums[i];
nums[i] = temp;
break;
}
}
}
//sort(nums.begin() + position + 1, nums.end());
reverse(nums.begin() + position + 1, nums.end());
}
};