forked from bakiyaswanth/hacktoberfest21
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext Permutation.py
More file actions
39 lines (30 loc) · 1.06 KB
/
Next Permutation.py
File metadata and controls
39 lines (30 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import sys
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if(len(nums)<=1):
return
maxPrev = nums[-1]
for i in range(len(nums)-2, -2, -1):
if(i>=0 and nums[i] < maxPrev):
break
maxPrev = max(maxPrev, nums[i])
if(i>=0):
minAfter = sys.maxsize
minAfterIndex = i+1
temp = nums[i]
for j in range(len(nums)-1,i,-1):
if(nums[j] > temp and nums[j] < minAfter):
minAfter = nums[j]
minAfterIndex = j
nums[minAfterIndex] = temp
nums[i] = minAfter
start, end = i+1, len(nums)-1
while(start < end):
nums[start], nums[end] = nums[end], nums[start]
start+=1
end-=1
else:
nums.sort()