Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
The replacement must be in place and use only constant extra memory.
Example 1:
Input: nums = [1,2,3]
Output: [1,3,2]
Example 2:
Input: nums = [3,2,1]
Output: [1,2,3]
Example 3:
Input: nums = [1,1,5]
Output: [1,5,1]
Example 4:
Input: nums = [1]
Output: [1]
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
题意
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
排列组合 且 下一个组合 的数字比 上一个大 : EX 1 EX 3
除了 到底的排列 : EX 2 ,则 全部翻转(reverse)过来
解法
Tip Source: LeetCode 31 / Solution / Approach 2: Single Pass Approach
图像解法动画
Code
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
#for i in range(len(nums)):
i = len(nums)-2
flag = 0
while i >=0:
if nums[i]<nums[i+1]:
flag = 1
print(nums[i])
j = i+1
while nums[j]<nums[i]:
j+=1
#print(nums[j])
print(nums[j])
if nums[j] > nums[i]:
tmp = nums[j]
nums[j] = nums[i]
nums[i] = tmp
break
i-=1
if flag ==0:
nums=nums.reverse()
print(nums)
Result 电脑解Code,躺床时继续想个,想通则手机AC(Success)
<<: UIView , UIViewController Life Cycle 常见问题
参与者指定由用户或与主体交互的任何其他系统所扮演的角色。它可能代表人类用户、外部硬件或其他主体所扮演...
在 Day2 提到什麽是用於生产的机械学习 ML in Production ,今天来谈用於生产的机...
前几天总共介绍了4种不同的储存方式,今天要来介绍最後一种: Cloud FireStore。 Fir...
同步发表於个人网站 LuaRocks LuaRocks是类似npm、pip这样的套件管理工具,你可...
前言 相信点开的你,可能是对购物车系统有兴趣亦或是有需求。因为疫情的关系在家自学,而选择了这个主题,...