Created
July 22, 2018 12:53
-
-
Save waynejo/f3db459cb37c88e042e9fbe0a269ea88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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