mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-10 13:37:33 +08:00
Update 031-Next Permutation
Changes: ---------- * Devided resposiblity with using functions. * Slice in already a reference type in go, means in passes actual slice(not a copy) to functions, that's why using pointers in swap and reverse functions look redundant in my opinion. Discussion: -------------- https://leetcode.com/problems/next-permutation/discuss/1554932/Go-Submission-with-Explanation
This commit is contained in:
@ -1,31 +1,55 @@
|
|||||||
|
// https://leetcode.com/problems/next-permutation/discuss/1554932/Go-Submission-with-Explanation
|
||||||
|
// Time O(N) , Space: O(1)
|
||||||
|
|
||||||
package leetcode
|
package leetcode
|
||||||
|
|
||||||
|
// [2,(3),6,5,4,1] -> 2,(4),6,5,(3),1 -> 2,4, 1,3,5,6
|
||||||
func nextPermutation(nums []int) {
|
func nextPermutation(nums []int) {
|
||||||
i, j := 0, 0
|
var n = len(nums)
|
||||||
for i = len(nums) - 2; i >= 0; i-- {
|
var pIdx = checkPermutationPossibility(nums)
|
||||||
if nums[i] < nums[i+1] {
|
if pIdx == -1 {
|
||||||
|
reverse(nums, 0, n-1)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var rp = len(nums) - 1
|
||||||
|
// start from right most to leftward,find the first number which is larger than PIVOT
|
||||||
|
for rp > 0 {
|
||||||
|
if nums[rp] > nums[pIdx] {
|
||||||
|
swap(nums, pIdx, rp)
|
||||||
break
|
break
|
||||||
|
} else {
|
||||||
|
rp--
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if i >= 0 {
|
// Finally, Reverse all elements which are right from pivot
|
||||||
for j = len(nums) - 1; j > i; j-- {
|
reverse(nums, pIdx+1, n-1)
|
||||||
if nums[j] > nums[i] {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
swap(&nums, i, j)
|
|
||||||
}
|
|
||||||
reverse(&nums, i+1, len(nums)-1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func reverse(nums *[]int, i, j int) {
|
func swap(nums []int, i, j int) {
|
||||||
for i < j {
|
nums[i], nums[j] = nums[j], nums[i]
|
||||||
swap(nums, i, j)
|
}
|
||||||
i++
|
|
||||||
j--
|
func reverse(nums []int, s int, e int) {
|
||||||
|
for s < e {
|
||||||
|
swap(nums, s, e)
|
||||||
|
s++
|
||||||
|
e--
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func swap(nums *[]int, i, j int) {
|
// checkPermutationPossibility returns 1st occurrence Index where
|
||||||
(*nums)[i], (*nums)[j] = (*nums)[j], (*nums)[i]
|
// value is in decreasing order(from right to left)
|
||||||
|
// returns -1 if not found(it's already in its last permutation)
|
||||||
|
func checkPermutationPossibility(nums []int) (idx int) {
|
||||||
|
// search right to left for 1st number(from right) that is not in increasing order
|
||||||
|
var rp = len(nums) - 1
|
||||||
|
for rp > 0 {
|
||||||
|
if nums[rp-1] < nums[rp] {
|
||||||
|
idx = rp - 1
|
||||||
|
return idx
|
||||||
|
}
|
||||||
|
rp--
|
||||||
|
}
|
||||||
|
return -1
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user