Advertisement
aero2146

Next Permutation

Apr 10th, 2020
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. class Solution:
  2.     def nextPermutation(self, nums: List[int]) -> None:
  3.         """
  4.        Do not return anything, modify nums in-place instead.
  5.        """
  6.         def reverse(lo, hi, nums):
  7.             while lo < hi:
  8.                 nums[lo], nums[hi] = nums[hi], nums[lo]
  9.                 lo += 1
  10.                 hi -= 1
  11.        
  12.         def swap(i, j, nums):
  13.             nums[i], nums[j] = nums[j], nums[i]
  14.            
  15.         if len(nums) < 2:
  16.             return
  17.            
  18.         # Find the first minimum from the right
  19.         i = len(nums)-2
  20.         while i >= 0 and nums[i+1] <= nums[i]:
  21.             i -= 1
  22.        
  23.         # Find the smallest number that is larger than nums[i]
  24.         if i >= 0:
  25.             j = len(nums)-1
  26.             while j >= 0 and nums[j] <= nums[i]:
  27.                 j -= 1
  28.            
  29.  
  30.             # Swap the elements
  31.             swap(i,j,nums)
  32.  
  33.             # Reverse elements
  34.         reverse(i+1, len(nums)-1, nums)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement