1
+ # A permutation of an array of integers is an arrangement of its members
2
+ # into a sequence or linear order.
3
+
4
+ # For example, for arr = [1,2,3], the following are all the permutations
5
+ # of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1].
6
+ # The next permutation of an array of integers is the next lexicographically
7
+ # greater permutation of its integer. More formally, if all the permutations
8
+ # of the array are sorted in one container according to their lexicographical
9
+ # order, then the next permutation of that array is the permutation that follows
10
+ # it in the sorted container. If such arrangement is not possible, the array
11
+ # must be rearranged as the lowest possible order (i.e., sorted in ascending order).
12
+
13
+ # For example, the next permutation of arr = [1,2,3] is [1,3,2].
14
+ # Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
15
+ # While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not
16
+ # have a lexicographical larger rearrangement.
17
+ # Given an array of integers nums, find the next permutation of nums.
18
+
19
+ # The replacement must be in place and use only constant extra memory.
20
+
21
+
22
+ # Example 1:
23
+ # Input: nums = [1,2,3]
24
+ # Output: [1,3,2]
25
+
26
+ # Example 2:
27
+ # Input: nums = [3,2,1]
28
+ # Output: [1,2,3]
29
+
30
+ # Example 3:
31
+ # Input: nums = [1,1,5]
32
+ # Output: [1,5,1]
33
+
34
+
35
+ # Constraints:
36
+ # 1 <= nums.length <= 100
37
+ # 0 <= nums[i] <= 100
38
+
39
+
40
+ from typing import List
41
+ class Solution :
42
+ def nextPermutation (self , nums : List [int ]) -> None :
43
+ """
44
+ Do not return anything, modify nums in-place instead.
45
+ """
46
+ n = len (nums )
47
+ j = - 1
48
+
49
+ for i in range (n - 2 , - 1 , - 1 ):
50
+ if nums [i ] < nums [i + 1 ]:
51
+ j = i
52
+ break
53
+
54
+ if j == - 1 :
55
+ nums .reverse ()
56
+ return
57
+
58
+ for i in range (n - 1 , j , - 1 ):
59
+ if nums [i ] > nums [j ]:
60
+ nums [i ], nums [j ] = nums [j ], nums [i ]
61
+ break
62
+
63
+ l , r = j + 1 , n - 1
64
+ while l < r :
65
+ nums [l ], nums [r ] = nums [r ], nums [l ]
66
+ l += 1
67
+ r -= 1
0 commit comments