-
Notifications
You must be signed in to change notification settings - Fork 0
/
Next_Permutation.py
46 lines (33 loc) · 1.09 KB
/
Next_Permutation.py
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
40
41
42
43
44
45
46
#User function Template for python3
class Solution:
def reverse(self, arr, start, end):
while start < end:
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start += 1
end -= 1
def return_pivot(self, arr):
i = len(arr) - 2
while i>=0:
if arr[i] < arr[i+1]:
return i
i -= 1
return -1
def find_greater(self, arr, pivot):
i = len(arr) - 1
while i > pivot:
if arr[i] > arr[pivot]:
return i
i -= 1
return -1
def nextPermutation(self, arr):
pivot = self.return_pivot(arr)
if pivot == -1:
self.reverse(arr, 0, len(arr) -1)
return
index = self.find_greater(arr, pivot)
tmp = arr[index]
arr[index] = arr[pivot]
arr[pivot] = tmp
self.reverse(arr, pivot + 1, len(arr) - 1)