Skip to content

Instantly share code, notes, and snippets.

@waynejo
Created July 22, 2018 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waynejo/f3db459cb37c88e042e9fbe0a269ea88 to your computer and use it in GitHub Desktop.
Save waynejo/f3db459cb37c88e042e9fbe0a269ea88 to your computer and use it in GitHub Desktop.
import (
"strings"
"strconv"
)
func nextPermutation(nums []int) {
var startPoint = -1
var endPoint = -1
// find start point
lenOfNums := len(nums)
for idx := lenOfNums - 2; idx >= 0; idx-- {
if nums[idx] < nums[idx + 1] {
startPoint = idx
break
}
}
if -1 != startPoint {
// find end point
for idx := startPoint + 1; idx < lenOfNums; idx++ {
if nums[startPoint] < nums[idx] && (-1 == endPoint || nums[idx] <= nums[endPoint]) {
endPoint = idx
}
}
// swap
nums[startPoint], nums[endPoint] = nums[endPoint], nums[startPoint]
}
// reverse post part of array
halfOfNumOfReverse := (lenOfNums - startPoint - 1) / 2
for idx := 1; idx <= halfOfNumOfReverse; idx++ {
oneIdx := startPoint + idx
anotherIdx := lenOfNums - idx
nums[oneIdx], nums[anotherIdx] = nums[anotherIdx], nums[oneIdx]
}
// print results
var outputs []string
for _, i := range nums {
outputs = append(outputs, strconv.Itoa(i))
}
println(strings.Join(outputs, " "))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment