Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 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.         """
  7.        if strictly descending, reverse and return
  8.        
  9.        3 1 2 -> 3 2 1
  10.        3 1 4 -> 3 4 1
  11.        2 4 0 -> 4 0 2
  12.        2 4 0 3 -> 2 4 3 0
  13.        2 4 3 0 -> 3 0 2 4
  14.        2 9 1 1 -> 9 1 1 2
  15.        2 1 3 0 -> 2 3 0 1
  16.        
  17.        starting from right
  18.        first time the next val is less than the current val:
  19.        swap current val and next val
  20.        sort rest of list from least to greatest
  21.        doesn't work -- 2 4 3 0 would be 4 0 2 3, should be 3 0 2 4
  22.        
  23.        find the last descending run -- for 2 4 3 0 would be "4 3 0"
  24.        look at next number -- for 2 4 3 0 woul dbe "2"
  25.        find the first number greater than "2", would be "3"
  26.        swap the "next" and "first greater" number
  27.        sort the indices of the last descending run, ascending
  28.        if there is no first greater number:
  29.        """
  30.        
  31.         ptr = len(nums) - 1
  32.        
  33.         while ptr > 0:
  34.             next_ptr = ptr - 1
  35.             if nums[next_ptr] < nums[ptr]:
  36.                 # the longest run is from ptr to the end of the array
  37.                 # the longest run is from greatest to least, left to right
  38.                 # we want to find the first value, from right to left, that is
  39.                 # greater than nums[ptr_next]
  40.                 target = nums[next_ptr]
  41.                 # TODO: maybe use some kind of binary search here instead
  42.                 # bisect doesn't deal with reverse-order lists :(
  43.                 # maybe reverse the list with [::-1]
  44.                 target_idx = len(nums) - 1
  45.                 while nums[target_idx] <= target:
  46.                     target_idx -= 1
  47.                 # nums[target_idx] is the first number greater than target
  48.                 # we want to swap nums[next_ptr] and nums[target_idx]
  49.                 nums[next_ptr], nums[target_idx] = nums[target_idx], nums[next_ptr]
  50.                 # now sort the rest of the list
  51.                 break
  52.             ptr -= 1
  53.         # we looked at the whole array and it's all strictly descending
  54.         # reverse the whole thing
  55.         nums[ptr:] = sorted(nums[ptr:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement