forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
next-permutation.py
48 lines (42 loc) · 1.19 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
47
48
# Time: O(n)
# Space: O(1)
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
k, l = -1, 0
for i in reversed(xrange(len(nums)-1)):
if nums[i] < nums[i+1]:
k = i
break
else:
nums.reverse()
return
for i in reversed(xrange(k+1, len(nums))):
if nums[i] > nums[k]:
l = i
break
nums[k], nums[l] = nums[l], nums[k]
nums[k+1:] = nums[:k:-1]
# Time: O(n)
# Space: O(1)
class Solution2(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
k, l = -1, 0
for i in xrange(len(nums)-1):
if nums[i] < nums[i+1]:
k = i
if k == -1:
nums.reverse()
return
for i in xrange(k+1, len(nums)):
if nums[i] > nums[k]:
l = i
nums[k], nums[l] = nums[l], nums[k]
nums[k+1:] = nums[:k:-1]