Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
My code:
class Solution:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
#Find the largest index k such that nums[k] < nums[k + 1]. If no such index exists, the permutation is sorted in descending order, just reverse it to ascending order and we are done. For example, the next permutation of [3, 2, 1] is [1, 2, 3].
#Find the largest index l greater than k such that nums[k] < nums[l].
##Swap nums[k] and nums[l].
#Reverse the sub-array from nums[k + 1] to nums[nums.size() - 1].
#Actually,i am confused by the question. Personally, just follow the instructions and carry out it
print(nums)
keep_k=-1
for k in range(len(nums)-1):
if nums[k]<nums[k+1]:
keep_k=k
if keep_k==-1:
nums.sort()
return
max_value=nums[keep_k]
for l in range(keep_k+1,len(nums)):
if nums[l]>max_value:
keep_l=l
#Swap operation
tmp_data=nums[keep_l]
nums[keep_l]=nums[keep_k]
nums[keep_k]=tmp_data
i=keep_k+1
j=len(nums)-1
while i<j:
tmp_data=nums[i]
nums[i]=nums[j]
nums[j]=tmp_data
i+=1
j-=1
print(nums)
return
Solution:
https://leetcode.com/problems/next-permutation