-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path31.cpp
More file actions
43 lines (39 loc) · 1.14 KB
/
31.cpp
File metadata and controls
43 lines (39 loc) · 1.14 KB
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
// Author: btjanaka (Bryon Tjanaka)
// Problem: (Leetcode) 31
// Title: Next Permutation
// Link: https://leetcode.com/problems/next-permutation
// Idea: See
// https://www.nayuki.io/page/next-lexicographical-permutation-algorithm
// Difficulty: medium
// Tags: implementation, arrays
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
if (n == 0 || n == 1) return;
// Find beginning of non-increasing suffix
int suffix = n - 1;
while (suffix > 0 && nums[suffix] <= nums[suffix - 1]) {
--suffix;
}
// Only go looking for a successor if the suffix is not occupying the whole
// array.
if (suffix != 0) {
int pivot = nums[suffix - 1];
int next;
for (next = n - 1; nums[next] <= pivot; --next)
;
// Swap the successor and pivot
int tmp = nums[next];
nums[next] = nums[suffix - 1];
nums[suffix - 1] = tmp;
}
// Reverse suffix
int suffix_len = n - suffix;
for (int i = 0; i < suffix_len / 2; ++i) {
int tmp = nums[i + suffix];
nums[i + suffix] = nums[n - i - 1];
nums[n - i - 1] = tmp;
}
}
};