Skip to content

Instantly share code, notes, and snippets.

@willwangcc
Created July 14, 2017 00:44
Show Gist options
  • Save willwangcc/fd32c5966c805742ab31ae66b09816ab to your computer and use it in GitHub Desktop.
Save willwangcc/fd32c5966c805742ab31ae66b09816ab to your computer and use it in GitHub Desktop.
# 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