Created
January 7, 2019 03:02
-
-
Save chairco/b5b2b3e8ecaedd3ad5ed1b18d3f675c5 to your computer and use it in GitHub Desktop.
leetcode 31 temp
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
#-*- coding: utf-8 -*- | |
def nextPermutation(nums): | |
""" | |
:type nums: List[int] | |
:rtype: void Do not return anything, modify nums in-place instead. | |
""" | |
''' | |
for i in range(len(nums)-1, 0, -1): | |
if nums[i] < nums[i-1]: | |
swap = nums[i-1] | |
for j in range(i, len(nums)): | |
if swap > nums[j]: | |
nums[i-1], nums[j] = nums[j], swap | |
return nums | |
''' | |
i = len(nums) - 2 | |
while i >= 0 and nums[i+1] <= nums[i]: | |
i -= 1 | |
if i >= 0: | |
j = len(nums) - 1 | |
while j >= 0 and nums[j] <= nums[i]: | |
j -= 1 | |
nums = swap(nums, i, j) | |
nums = reverse(nums, i+1) | |
return nums | |
def reverse(nums, start): | |
i, j = start, len(nums) - 1 | |
while i < j: | |
swap(nums, i, j) | |
i += 1 | |
j -= 1 | |
return nums | |
def swap(nums, i, j): | |
temp = nums[i] | |
nums[i] = nums[j] | |
nums[j] = temp | |
return nums | |
if __name__ == '__main__': | |
print(nextPermutation(nums=[1,2,3])) #[1,3,2] | |
print(nextPermutation(nums=[3,2,1])) #[1,2,3] | |
print(nextPermutation(nums=[5,7,9,8,6])) #[5,8,6,7,9] | |
print(nextPermutation(nums=[9,5,4,3,2,1])) #[1,2,3,4,5,9] | |
print(nextPermutation(nums=[1,5,8,4,7,6,5,3,1])) #[1,5,8,5,1,3,4,6,7] |
Author
chairco
commented
Jan 7, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment