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 的新序列,如果没有找到(即原序列正好是非升序排列),则直接返回升序序列。
解题思路:
1. 要使得新序列刚好比原序列大 1 ,那么就是尽量在原序列的低位进行交换;
2. 以序列的倒数第二位开始(此处以 left 指针指出)作为可能的待交换点,从序列的末尾向前搜索(以 right 指针指出),寻找第一个大于这个可能交换点的值的数字;
3. 如果找到,则交换 left 和 right ,此时可以保证这个新序列比原序列大,但是不能保证正好大 1 ,所以对再 left 之后的元素进行排序,保证正好大 1;
4. 如果没找到,那么 left--,作为新的可能交换点,重复以上步骤。
完整代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <stack>
using namespace std;
#define MAX_INT (int)0x7FFFFFFF
#define MIN_INT (int)0x80000000
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int right = nums.size()-1;
int left = nums.size()-2;
while(left >= 0) {
right = nums.size()-1;
while(right > left && nums[right] <= nums[left])right--;
if(right != left) {
int tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
break;
}
left--;
}
sort(nums.begin()+left+1,nums.end());
}
};
void main()
{
int tmp[] = {1,2,4,3,5};
Solution s;
vector<int> nums(&tmp[0],&tmp[4]);
s.nextPermutation(nums);
//cout << <<endl;
}