Skip to content

Commit 5c692e0

Browse files
authored
Create previous-permutation-with-one-swap.py
1 parent a34ebd7 commit 5c692e0

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def prevPermOpt1(self, A):
6+
"""
7+
:type A: List[int]
8+
:rtype: List[int]
9+
"""
10+
for left in reversed(xrange(len(A)-1)):
11+
if A[left] > A[left+1]:
12+
break
13+
else:
14+
return A
15+
right = len(A)-1
16+
while A[left] <= A[right]:
17+
right -= 1
18+
while A[right-1] == A[right]:
19+
right -= 1
20+
A[left], A[right] = A[right], A[left]
21+
return A

0 commit comments

Comments
 (0)