Skip to content

Commit c8c227a

Browse files
authored
Update next-permutation.cpp
1 parent 80f2130 commit c8c227a

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

C++/next-permutation.cpp

+25-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,30 @@
22
// Space: O(1)
33

44
class Solution {
5+
public:
6+
void nextPermutation(vector<int>& nums) {
7+
int pivot = -1;
8+
for (int i = nums.size() - 2; i >= 0; --i) {
9+
if (nums[i] < nums[i + 1]) {
10+
pivot = i;
11+
break;
12+
}
13+
}
14+
if (pivot == -1) {
15+
reverse(begin(nums), end(nums));
16+
return;
17+
}
18+
for (int i = nums.size() - 1; i > pivot; --i) {
19+
if (nums[i] > nums[pivot]) {
20+
swap(nums[pivot], nums[i]);
21+
break;
22+
}
23+
}
24+
reverse(begin(nums) + pivot + 1, end(nums));
25+
}
26+
};
27+
28+
class Solution2 {
529
public:
630
void nextPermutation(vector<int> &num) {
731
nextPermutation(num.begin(), num.end());
@@ -35,7 +59,7 @@ class Solution {
3559
}
3660
};
3761

38-
class Solution2 {
62+
class Solution3 {
3963
public:
4064
void nextPermutation(vector<int> &num) {
4165
next_permutation(num.begin(), num.end());

0 commit comments

Comments
 (0)