-
Notifications
You must be signed in to change notification settings - Fork 0
/
0031.cpp
57 lines (52 loc) · 1.47 KB
/
0031.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
class Solution {
public:
void nextPermutation(vector<int>& nums) {
// func1(nums);
return func2(nums);
}
void func1(vector<int>& nums) {
next_permutation(nums.begin(), nums.end());
}
void func2(vector<int>& nums) {
int partition_index = findPartition(nums);
if (partition_index == -1) {
reverse(nums, 0, nums.size()-1);
return;
}
int change_index = findChange(nums, partition_index);
swap(nums, partition_index, change_index);
reverse(nums, partition_index+1, nums.size() - 1);
}
// return partition number index
int findPartition(vector<int>& nums) {
int i = nums.size() - 2;
while (i >= 0 && nums[i] >= nums[i+1]) {
i--;
}
// cout << "findPartition i=" << i << endl;
return i;
}
// return change number index
int findChange(vector<int>& nums, int partition_index) {
int i = nums.size() - 1;
while (i > partition_index && nums[i] <= nums[partition_index]) {
i--;
}
// cout << "findChange i=" << i << endl;
return i;
}
void swap(vector<int>& nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
return;
}
void reverse(vector<int>& nums, int lo, int hi) {
while (lo < hi) {
swap(nums, lo, hi);
lo++;
hi--;
}
return;
}
};