forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
previous-permutation.cpp
48 lines (42 loc) · 1.2 KB
/
previous-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
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param nums: An array of integers
* @return: An array of integers that's previous permuation
*/
vector<int> previousPermuation(vector<int> &nums) {
int k = -1, l = 0;
// Find the last index k before the increasing sequence.
for (int i = 0; i < nums.size() - 1; ++i) {
if (nums[i] > nums[i + 1]) {
k = i;
}
}
if (k >= 0) {
// Find the largest number which is smaller than the value of the index k,
// and swap the values.
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] < nums[k]) {
l = i;
}
}
swap(nums[k], nums[l]);
}
// Reverse the sequence after the index k.
reverse(nums.begin() + k + 1, nums.end());
return nums;
}
};
class Solution2 {
public:
/**
* @param nums: An array of integers
* @return: An array of integers that's previous permuation
*/
vector<int> previousPermuation(vector<int> &nums) {
prev_permutation(nums.begin(), nums.end());
return nums;
}
};