Created
July 3, 2019 03:25
-
-
Save athulmurali/0ed2144c6114cce7dded929b0988c615 to your computer and use it in GitHub Desktop.
nextPermutation
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
class Solution: | |
def nextPermutation(self, nums: List[int]) -> None: | |
n = len(nums) | |
prev = -float("inf") | |
ind = n -1 | |
for i in range(n): | |
ind = n - i -1 | |
if nums[ind] < prev: | |
j = n -1 | |
while(nums[j] <= nums[ind] and j > ind) : | |
j -=1 | |
# swap current ind element with next greatest element to current_ind of all the elements to the right of current ind | |
nums[j], nums[ind] = nums[ind] , nums[j] | |
#sort current ind + 1 to right end | |
nums[ind + 1: ] = sorted(nums[ind + 1: ]) | |
return | |
else: | |
prev = nums[ind] | |
if ind == 0: | |
nums.sort() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Latest
https://repl.it/repls/UpbeatHumongousAtoms