File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ # time complexity: O(n^2)
2+ # space complexity: O(1)
3+ from typing import List
4+
5+
6+ class Solution :
7+ def nextPermutation (self , nums : List [int ]) -> None :
8+ if nums == sorted (nums , key = lambda x : - x ):
9+ nums .sort ()
10+ return
11+
12+ for i in range (len (nums ) - 1 , 0 , - 1 ):
13+ if nums [i - 1 ] < nums [i ]:
14+ minIdx , minVal = len (nums ), float ('inf' )
15+ for j in range (len (nums ) - 1 , i - 1 , - 1 ):
16+ if nums [j ] > nums [i - 1 ] and nums [j ] < minVal :
17+ minVal = nums [j ]
18+ minIdx = j
19+ nums [i - 1 ], nums [minIdx ] = nums [minIdx ], nums [i - 1 ]
20+
21+ while True :
22+ swapped = False
23+ for k in range (i , len (nums ) - 1 ):
24+ if nums [k ] > nums [k + 1 ]:
25+ swapped = True
26+ nums [k ], nums [k + 1 ] = nums [k + 1 ], nums [k ]
27+ if swapped == False :
28+ break
29+
30+ return
31+
32+
33+ nums = [1 , 2 , 3 ]
34+ print (Solution ().nextPermutation (nums ))
35+ nums = [3 , 2 , 1 ]
36+ print (Solution ().nextPermutation (nums ))
37+ nums = [1 , 1 , 5 ]
38+ print (Solution ().nextPermutation (nums ))
You can’t perform that action at this time.
0 commit comments