Skip to content

Commit 89ad531

Browse files
committed
Time: 0 ms (100%), Space: 17.8 MB (35.06%) - LeetHub
1 parent 2a72a4e commit 89ad531

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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))

0 commit comments

Comments
 (0)