标签:ems 说明 stream const cal ons names algo namespace
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
暴力解决,O(n!) 的时间复杂度求出数组的全排列,然后返回比当前排列大的序列中最小的。
时间复杂度:O(n);空间复杂度:O(1)
不失一般性,假设数组如图所示。我们从后往前遍历数组,比较相邻的两个数,直到出现前一个数小于后一个数时,循环停止。如图中 a[i-1] < a[i],循环的结果有以下两点说明:
具体实现的逻辑参看代码。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution{
public:
void nextPermutation(vector<int>& nums) {
if(nums.empty())
return;
int isplit = -1;
for(int i=nums.size()-1; i>0; i--){
if(nums[i-1] < nums[i]){
isplit = i-1;
break;
}
}
// if isplit == -1, which indicate nums is in descending
// otherwhise, [isplit+1, n-1] is descending
if(isplit == -1){
reverse(nums, 0, nums.size()-1);
}else{
// construct next permutation
// find the smallest one from the numbers which larger than nums[isplit]
int ismallest = nums.size()-1;
while(ismallest>isplit && nums[ismallest] <= nums[isplit])
ismallest--;
// nums[ismallest] > nums[isplit] >= nums[ismallest+1, ... , n-1]
// and nums[isplit+1, ismallest-1] >= nums[ismallest] >= nums[ismallest+1,..,n-1]
swap(nums[isplit], nums[ismallest]);
// nums[isplit+1, ... , n-1] still in descending
// so just reverse
reverse(nums, isplit+1, nums.size()-1);
}
}
void reverse(vector<int>& nums, int ileft, int iright){
while(ileft < iright){
swap(nums[ileft], nums[iright]);
ileft++;
iright--;
}
}
};
int main()
{
return 0;
}
[array] leetcode - 31. Next Permutation - Medium
标签:ems 说明 stream const cal ons names algo namespace
原文地址:http://www.cnblogs.com/fanling999/p/7837502.html