-
Notifications
You must be signed in to change notification settings - Fork 257
/
next-permutation-ii.cpp
39 lines (36 loc) · 982 Bytes
/
next-permutation-ii.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
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param nums: a vector of integers
* @return: return nothing (void), do not return anything, modify nums in-place instead
*/
void nextPermutation(vector<int> &nums) {
int k = -1, l = 0;
for (int i = 0; i < nums.size() - 1; ++i) {
if (nums[i] < nums[i + 1]) {
k = i;
}
}
if (k >= 0) {
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > nums[k]) {
l = i;
}
}
swap(nums[k], nums[l]);
}
reverse(nums.begin() + k + 1, nums.end());
}
};
class Solution2 {
public:
/**
* @param nums: a vector of integers
* @return: return nothing (void), do not return anything, modify nums in-place instead
*/
void nextPermutation(vector<int> &nums) {
next_permutation(nums.begin(), nums.end());
}
};