-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode31_next_permutation.cpp
78 lines (67 loc) · 1.69 KB
/
leetcode31_next_permutation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* @file leetcode31_next_permutation.cpp
* @author wangguibao(https://github.com/wangguibao)
* @date 2021/12/19 15:23:32
* @brief https://leetcode.com/problems/next-permutation/
* @ref https://www.keithschwarz.com/interesting/code/?dir=next-permutation
*
**/
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
class Solution {
public:
void nextPermutation(std::vector<int>& nums) {
int left = -1;
for (int i = nums.size() - 2; i >= 0; --i) {
if (nums[i] < nums[i + 1]) {
left = i;
break;
}
}
int right = 0;
for (size_t i = nums.size() - 1; i > left; --i) {
if (nums[i] > nums[left]) {
right = i;
std::swap(nums[left], nums[right]);
break;
}
}
int lo = left + 1;
int hi = nums.size() - 1;
while (lo < hi) {
std::swap(nums[lo], nums[hi]);
++lo;
--hi;
}
}
};
int main() {
int n;
std::vector<int> nums;
while (1) {
n = 0;
std::cout << "Number of elements: ";
std::cin >> n;
if (n <= 0) {
return 0;
}
std::cout << n << " integers: " << std::endl;
nums.clear();
int ele;
for (int i = 0; i < n; ++i) {
std::cin >> ele;
nums.push_back(ele);
}
Solution solution;
solution.nextPermutation(nums);
std::cout << "[";
for (size_t i = 0; i < nums.size(); ++i) {
std::cout << nums[i] << " ";
}
std::cout << "]" << std::endl;
}
return 0;
}