|
1 |
| -// https://leetcode.com/problems/next-permutation/discuss/1554932/Go-Submission-with-Explanation |
2 |
| -// Time O(N) , Space: O(1) |
3 |
| - |
4 | 1 | package leetcode
|
5 | 2 |
|
6 |
| -// [2,(3),6,5,4,1] -> 2,(4),6,5,(3),1 -> 2,4, 1,3,5,6 |
| 3 | +// 解法一 |
7 | 4 | func nextPermutation(nums []int) {
|
| 5 | + i, j := 0, 0 |
| 6 | + for i = len(nums) - 2; i >= 0; i-- { |
| 7 | + if nums[i] < nums[i+1] { |
| 8 | + break |
| 9 | + } |
| 10 | + } |
| 11 | + if i >= 0 { |
| 12 | + for j = len(nums) - 1; j > i; j-- { |
| 13 | + if nums[j] > nums[i] { |
| 14 | + break |
| 15 | + } |
| 16 | + } |
| 17 | + swap(&nums, i, j) |
| 18 | + } |
| 19 | + reverse(&nums, i+1, len(nums)-1) |
| 20 | +} |
| 21 | + |
| 22 | +func reverse(nums *[]int, i, j int) { |
| 23 | + for i < j { |
| 24 | + swap(nums, i, j) |
| 25 | + i++ |
| 26 | + j-- |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +func swap(nums *[]int, i, j int) { |
| 31 | + (*nums)[i], (*nums)[j] = (*nums)[j], (*nums)[i] |
| 32 | +} |
| 33 | + |
| 34 | +// 解法二 |
| 35 | +// [2,(3),6,5,4,1] -> 2,(4),6,5,(3),1 -> 2,4, 1,3,5,6 |
| 36 | +func nextPermutation1(nums []int) { |
8 | 37 | var n = len(nums)
|
9 | 38 | var pIdx = checkPermutationPossibility(nums)
|
10 | 39 | if pIdx == -1 {
|
11 |
| - reverse(nums, 0, n-1) |
| 40 | + reverse(&nums, 0, n-1) |
12 | 41 | return
|
13 | 42 | }
|
14 | 43 |
|
15 | 44 | var rp = len(nums) - 1
|
16 | 45 | // start from right most to leftward,find the first number which is larger than PIVOT
|
17 | 46 | for rp > 0 {
|
18 | 47 | if nums[rp] > nums[pIdx] {
|
19 |
| - swap(nums, pIdx, rp) |
| 48 | + swap(&nums, pIdx, rp) |
20 | 49 | break
|
21 | 50 | } else {
|
22 | 51 | rp--
|
23 | 52 | }
|
24 | 53 | }
|
25 | 54 | // Finally, Reverse all elements which are right from pivot
|
26 |
| - reverse(nums, pIdx+1, n-1) |
27 |
| -} |
28 |
| - |
29 |
| -func swap(nums []int, i, j int) { |
30 |
| - nums[i], nums[j] = nums[j], nums[i] |
31 |
| -} |
32 |
| - |
33 |
| -func reverse(nums []int, s int, e int) { |
34 |
| - for s < e { |
35 |
| - swap(nums, s, e) |
36 |
| - s++ |
37 |
| - e-- |
38 |
| - } |
| 55 | + reverse(&nums, pIdx+1, n-1) |
39 | 56 | }
|
40 | 57 |
|
41 | 58 | // checkPermutationPossibility returns 1st occurrence Index where
|
|
0 commit comments