-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#0031.next-permutation.rs
55 lines (51 loc) · 1.28 KB
/
#0031.next-permutation.rs
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
impl Solution {
pub fn next_permutation(nums: &mut Vec<i32>) {
let len = nums.len();
match len {
1 => {
return;
}
2 => {
Self::swap(nums, 0, 1);
return;
}
_ => {}
}
let mut index = 0;
if nums[len - 1] > nums[len - 2] {
Self::swap(nums, len - 1, len - 2);
return;
} else {
for i in (1..len - 1).rev() {
if nums[i] > nums[i - 1] {
index = i;
break;
}
}
Self::reverse(nums, index, len - 1);
if index == 0 {
return;
}
for i in index..len {
if nums[i] > nums[index - 1] {
Self::swap(nums, i, index - 1);
break;
}
}
}
}
fn reverse(nums: &mut Vec<i32>, i: usize, j: usize) {
let mut i = i;
let mut j = j;
while i < j {
Self::swap(nums, i, j);
i += 1;
j -= 1;
}
}
fn swap(nums: &mut Vec<i32>, i: usize, j: usize) {
let t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}