## [Leetcode]31. Next Permutation(C++)

### 题目描述

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

The replacement must be in place and use only constant extra memory.

### 例子

#### 例子 1

Input: `nums = [1,2,3]` Output: `[1,3,2]`

#### 例子 2

Input: `nums = [3,2,1]` Output: `[1,2,3]`

#### 例子 3

Input: `nums = [1,1,5]` Output: `[1,5,1]`

### Constraints

• `1 <= nums.length <= 100`
• `0 <= nums[i] <= 100`

### 解题思路

``````#include <vector>
#include <algorithm>

class Solution {
public:
void nextPermutation(std::vector<int>& nums) {
int right = nums.size() - 1;
int left = nums.size() - 2;
while (left >= 0 && nums[left] >= nums[left + 1]) --left;

if (left < 0) {
std::reverse(nums.begin(), nums.end());
return;
}

while (left < right && nums[right] <= nums[left]) --right;
std::swap(nums[right], nums[left]);
std::reverse(nums.begin() + left + 1, nums.end());
}
};
``````
• 时间复杂度: O(n)
• 空间复杂度: O(1)

GitHub 代码同步地址： 31.NextPermutation.cpp

Built with Hugo
Theme Stack designed by Jimmy