Created
July 14, 2017 00:44
-
-
Save willwangcc/fd32c5966c805742ab31ae66b09816ab 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
# Time: O(n) | |
# Space: O(1) | |
# 31 Next Permutation | |
# Edge case | |
''' | |
https://www.nayuki.io/res/next-lexicographical-permutation-algorithm/next-permutation-algorithm.png | |
''' | |
class Solution(object): | |
def nextPermutation(self, nums): | |
""" | |
:type nums: List[int] | |
:rtype: void Do not return anything, modify nums in-place instead. | |
""" | |
pivot, bigger = -1,0 | |
for i in xrange(len(nums) -1): | |
if nums[i] < nums[i+1]: | |
pivot = i | |
if pivot == -1: | |
nums.reverse() | |
return | |
for i in xrange(pivot + 1, len(nums)): | |
if nums[i] > nums[pivot]: | |
bigger = i | |
nums[pivot], nums[bigger] = nums[bigger], nums[pivot] | |
nums[pivot + 1:] = nums[:pivot:-1] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment