Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

 

 

 

 1 class Solution:
 2 
 3     def nextPermutation(self, a):
 4         """
 5         :type nums: List[int]
 6         :rtype: void Do not return anything, modify nums in-place instead.
 7         """
 8         def swap(a, i, j):
 9             temp = a[i]
10             a[i] = a[j]
11             a[j] = temp
12 
13         def reverces(a, i):
14             for k in range(int((len(a) - i) / 2)):
15                 swap(a, i + k, len(a) - k - 1)
16 
17         # 后找
18         i = len(a) - 2
19         while(i>=0 and a[i + 1] <= a[i]):
20             i -= 1
21 
22         # 小大
23         if(i >= 0):
24             j = len(a) - 1
25             while j >= 0 and a[j] <= a[i]:
26                 j -= 1
27             # 交换      
28             swap(a, i, j)
29             # 反转
30         reverces(a, i+1)

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-23
  • 2022-02-21
猜你喜欢
  • 2021-09-22
  • 2022-01-22
  • 2021-07-10
  • 2021-09-20
  • 2021-08-08
  • 2021-06-22
  • 2022-01-20
相关资源
相似解决方案