(Medium #31) Next Permutation
Problem
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
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 solution
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-1,0,-1):
if nums[i] > nums[i-1]:
start = i-1
# print("start", i-1)
for k in range(len(nums)-1,start,-1):
if nums[k] > nums[start]:
# print("end", k)
end = k
nums[start], nums[end] = nums[end], nums[start]
# nums = nums[:start+1] + nums[:start:-1]
for m in range(int((len(nums)-start)/2)):
# print(start+1+m, len(nums)-1-m)
nums[start+1+m], nums[len(nums)-1-m] = nums[len(nums)-1-m], nums[start+1+m]
# print("mod",nums)
# print(nums)
break
break
if i == 1:
nums.reverse()
Runtime: 44ms, Memory: 13.9MB
Referencedef nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-1,0,-1):
if nums[i] > nums[i-1]:
start = i-1
# print("start", i-1)
for k in range(len(nums)-1,start,-1):
if nums[k] > nums[start]:
# print("end", k)
end = k
nums[start], nums[end] = nums[end], nums[start]
# nums = nums[:start+1] + nums[:start:-1]
for m in range(int((len(nums)-start)/2)):
# print(start+1+m, len(nums)-1-m)
nums[start+1+m], nums[len(nums)-1-m] = nums[len(nums)-1-m], nums[start+1+m]
# print("mod",nums)
# print(nums)
break
break
if i == 1:
nums.reverse()
생각해보면 좋을 예시
- 147512→147521→151247
댓글
댓글 쓰기